factory_test_init: check state before starting factory program

This is the counter part of http://gerrit.chromium.org/gerrit/5867 ,
to verify state before starting factory UI.

BUG=chrome-os-partner:3107
TEST=see http://gerrit.chromium.org/gerrit/5867

Change-Id: Ibb20eb588fc914ce32fffec501303978b2870669
Reviewed-on: http://gerrit.chromium.org/gerrit/5868
Tested-by: Hung-Te Lin <hungte@chromium.org>
Reviewed-by: Hung-Te Lin <hungte@chromium.org>
diff --git a/factory.conf b/factory.conf
index 75789fc..2ed2b56 100644
--- a/factory.conf
+++ b/factory.conf
@@ -9,19 +9,22 @@
 stop on stopping system-services
 
 script
-  modprobe i2c-dev
-  cd /usr/local/autotest
-  eval $(./site_tests/suite_Factory/startx.sh)
-  date >>/var/log/factory.log
-  if [ ! -e factory_started ]; then
-    touch factory_started
-    cp -f site_tests/suite_Factory/control .
-    OPT=""
-  else
-    OPT="-c"
-  fi
+  SUITE_FACTORY=/usr/local/autotest/site_tests/suite_Factory
   FACTORY_LOG_FILE=/var/log/factory.log
   CONSOLE_LOG_FILE=/tmp/factory_console.log
+  modprobe i2c-dev
+  cd /usr/local/autotest
+  eval $($SUITE_FACTORY/startx.sh)
+  date >>$FACTORY_LOG_FILE
+  # Before continuing, we must make sure the control and control.state are both
+  # in good shape otherwise there will be only a blank screen.
+  OPT=""
+  if ! [ -e factory_started -a -e control ]; then
+    touch factory_started
+    cp -f $SUITE_FACTORY/control .
+  elif $SUITE_FACTORY/check_state control.state >>$FACTORY_LOG_FILE 2>&1; then
+    OPT="-c"
+  fi
   # Factory log will be uploaded so we must always preserve previous results.
   # Console log is just for UI to display, no need to be saved across sessions;
   # however in order to support writing by multiple processes, the file must be