Fix temporary source directory permission in toolkit install.

When factory toolkit installs into a test image, it leaves a set of
/tmp/selfgz* temporary source files because these files are owned
by root and the install script fails to remove them at the end.

Change the owner of the source directories back to the original user,
so they can be properly removed.

BUG=chrome-os-partner:30348
TEST=Manually make factory toolkit and install to a test image and
     verify that /tmp/selfgz* are removed.

Change-Id: I67b5a0ba6c6c1581d81cf66644d84a17d88259c4
Reviewed-on: https://chromium-review.googlesource.com/206977
Commit-Queue: Ricky Liang <jcliang@chromium.org>
Tested-by: Ricky Liang <jcliang@chromium.org>
Reviewed-by: Jon Salz <jsalz@chromium.org>
diff --git a/py/toolkit/installer.py b/py/toolkit/installer.py
index 2445acd..bab679d 100755
--- a/py/toolkit/installer.py
+++ b/py/toolkit/installer.py
@@ -210,14 +210,22 @@
       # may be hosed.  This is skipped for testing.
       # --force is necessary to allow goofy directory from prior
       # toolkit installations to be overwritten by the goofy symlink.
-      if self._sudo:
-        Spawn(['chown', '-R', 'root', src],
-              sudo=True, log=True, check_call=True)
-        Spawn(['chmod', '-R', 'go+rX', src],
-              sudo=True, log=True, check_call=True)
-      print '***   %s -> %s' % (src, dest)
-      Spawn(['rsync', '-a', '--force', src + '/', dest],
-            sudo=self._sudo, log=True, check_output=True)
+      try:
+        if self._sudo:
+          Spawn(['chown', '-R', 'root', src],
+                sudo=True, log=True, check_call=True)
+          Spawn(['chmod', '-R', 'go+rX', src],
+                sudo=True, log=True, check_call=True)
+        print '***   %s -> %s' % (src, dest)
+        Spawn(['rsync', '-a', '--force', src + '/', dest],
+              sudo=self._sudo, log=True, check_output=True)
+      finally:
+        # Need to change the source directory back to the original user, or the
+        # script in makeself will fail to remove the temporary source directory.
+        if self._sudo:
+          myuser = os.environ.get('USER')
+          Spawn(['chown', '-R', myuser, src],
+                sudo=True, log=True, check_call=True)
 
     self._SetTagFile('factory', self._tag_file, not self._no_enable)
     self._SetTagFile('host', self._host_tag_file, self._enable_host)