cros_sdk: avoid sudo to chmod when possible

Checking the permission of files is faster than assuming they're broken
and then running `sudo chmod`, so do just that.

BUG=None
TEST=run `cros_sdk --enter` with bad perms and see them fixed
TEST=run `cros_sdk --enter` with correct perms and see sudo skipped
TEST=the buildbot failure was due to other changes, not this one

Change-Id: Ie69b4e766e2e3652944e4723d091ce589d07a4f6
Reviewed-on: http://gerrit.chromium.org/gerrit/8028
Commit-Ready: Mike Frysinger <vapier@chromium.org>
Reviewed-by: Mike Frysinger <vapier@chromium.org>
Tested-by: Mike Frysinger <vapier@chromium.org>
diff --git a/sdk_lib/enter_chroot.sh b/sdk_lib/enter_chroot.sh
index 53f0cb2..fff5e4e 100755
--- a/sdk_lib/enter_chroot.sh
+++ b/sdk_lib/enter_chroot.sh
@@ -77,7 +77,10 @@
 AUTOMOUNT_PREF="/apps/nautilus/preferences/media_automount"
 SAVED_AUTOMOUNT_PREF_FILE="/tmp/.automount_pref"
 
-sudo chmod 0777 "$FLAGS_chroot/var/lock"
+# Avoid the sudo call if possible since it is a little slow.
+if [ $(stat -c %a "$FLAGS_chroot/var/lock") != 777 ]; then
+  sudo chmod 0777 "$FLAGS_chroot/var/lock"
+fi
 
 LOCKFILE="$FLAGS_chroot/var/lock/enter_chroot"
 SYNCERPIDFILE="${FLAGS_chroot}/var/tmp/enter_chroot_sync.pid"
@@ -349,8 +352,10 @@
     fi
 
     # Fix permissions on shared memory to allow non-root users access to POSIX
-    # semaphores.
-    sudo chmod -R 777 "${FLAGS_chroot}/dev/shm"
+    # semaphores.  Avoid the sudo call if possible (sudo is slow).
+    if [ -n "$(find "${FLAGS_chroot}/dev/shm" ! -perm 777)" ] ; then
+      sudo chmod -R 777 "${FLAGS_chroot}/dev/shm"
+    fi
   ) 200>>"$LOCKFILE" || die "setup_env failed"
 }