Allow early initialization for factory test mode.

We want to allow some initialization procedure in startup stage (before
boot-services starts running UI) so we can customize UI default settings and
upstart jobs for factory test mode.

To do that, the is_factory_mode (which reports true for both factory test and
installer mode) must be divided into two new functions: is_factory_test_mode and
is_factory_installer_mode.

The new factory-init.conf job is executed when boot-services starts, and runs
initialization script if it is available.

BUG=chrome-os-partner:30239
TEST=Manual: Built a Link test image, boots in factory and non-factory mode.
     Built a factory installer image and boots correctly.

Change-Id: I153baecb8bc66fa0199e9fb8bcf3c50a543f1c2c
Reviewed-on: https://chromium-review.googlesource.com/206676
Tested-by: Hung-Te Lin <hungte@chromium.org>
Reviewed-by: Gaurav Shah <gauravsh@chromium.org>
Commit-Queue: Hung-Te Lin <hungte@chromium.org>
diff --git a/factory_utils.sh b/factory_utils.sh
index 0fcd5cb..f73e331 100644
--- a/factory_utils.sh
+++ b/factory_utils.sh
@@ -2,17 +2,19 @@
 # Use of this source code is governed by a BSD-style license that can be
 # found in the LICENSE file.
 
-is_factory_mode() {
+is_factory_test_mode() {
   # The path to factory enabled tag. If this path exists in a debug build,
   # we assume factory test mode.
-  FACTORY_TAG_PATH="/mnt/stateful_partition/dev_image/factory/enabled"
+  local factory_tag_path="/mnt/stateful_partition/dev_image/factory/enabled"
+  crossystem "debug_build?1" && [ -f "${factory_tag_path}" ]
+}
 
-  # Factory mode can be either:
-  # 1. We are running factory tests if this is a debug build and factory
-  #    enabled tag exists.
-  # 2. We are running a factory installer.
-  (crossystem "debug_build?1" && [ -f "$FACTORY_TAG_PATH" ]) ||
-      [ -f /root/.factory_installer ]
+is_factory_installer_mode() {
+  [ -f /root/.factory_installer ]
+}
+
+is_factory_mode() {
+  is_factory_test_mode || is_factory_installer_mode
 }
 
 inhibit_if_factory_mode() {
diff --git a/test-init/factory-init.conf b/test-init/factory-init.conf
new file mode 100644
index 0000000..db36e7e
--- /dev/null
+++ b/test-init/factory-init.conf
@@ -0,0 +1,18 @@
+description    "Initialize factory test environment"
+author         "chromium-os-dev@chromium.org"
+
+# For factory test to perform early initialization Ex: changing UI start
+# parameters, disable or add upstart jobs...
+# Hint: ui.conf starts on "started boot-services", so this factory-init should
+# always run before UI starts.
+
+start on starting boot-services
+task
+
+script
+  . /usr/share/cros/factory_utils.sh
+  if is_factory_test_mode; then
+    factory_init="/usr/local/factory/init/startup"
+    [ -x "${factory_init}" ] && "${factory_init}"
+  fi
+end script