enter_chroot: auto generate user locales

Since we no longer force LC_ALL=C on everyone, the few times that perl
does get run by people, it spews the expected "Setting locale failed"
warnings.  This isn't as big a deal as with Debian systems as perl usage
is uncommon in Gentoo.

This is also highlights the long-existing small issue of only specific
locales being available in the chroot.  So for non US english speaking
users, they've been having non-optimal experiences.

So parse the user's active locale and automatically generate the missing
ones in the chroot so that when they do enter, things "just work".

BUG=chromium-os:19139
TEST=set locale to non-existent ones, enter_chroot, & verify locales are created

Change-Id: I43f809a1ee1472e4797edab0f32cecf582ea8b48
Reviewed-on: http://gerrit.chromium.org/gerrit/5986
Reviewed-by: David James <davidjames@chromium.org>
Tested-by: Mike Frysinger <vapier@chromium.org>
diff --git a/sdk_lib/enter_chroot.sh b/sdk_lib/enter_chroot.sh
index 0827432..2fd0d6a 100755
--- a/sdk_lib/enter_chroot.sh
+++ b/sdk_lib/enter_chroot.sh
@@ -314,6 +314,29 @@
       user.email "$(cd /tmp; git var GIT_COMMITTER_IDENT | \
         sed -e 's/.*<\([^>]*\)>.*/\1/')" || true
 
+    # Make sure user's requested locales are available
+    # http://crosbug.com/19139
+    locales=$(printf '%s\n' ${LANG} \
+      $LC_{ADDRESS,ALL,COLLATE,CTYPE,IDENTIFICATION,MEASUREMENT,MESSAGES} \
+      $LC_{MONETARY,NAME,NUMERIC,PAPER,TELEPHONE,TIME} | \
+      sort -u | sed '/^C$/d')
+    gen_locales=()
+    for l in ${locales}; do
+      if [[ ${l} == *.* ]]; then
+        enc=${l#*.}
+      else
+        enc="ISO-8859-1"
+      fi
+      case $(echo ${enc//-} | tr '[:upper:]' '[:lower:]') in
+        utf8) enc="UTF-8";;
+      esac
+      gen_locales=("${gen_locales[@]}" "${l} ${enc}")
+    done
+    if [[ ${#gen_locales[@]} -gt 0 ]] ; then
+      sudo -- chroot "$FLAGS_chroot" locale-gen -q -u \
+        -G "$(printf '%s\n' "${gen_locales[@]}")"
+    fi
+
     # Fix permissions on shared memory to allow non-root users access to POSIX
     # semaphores.
     sudo chmod -R 777 "${FLAGS_chroot}/dev/shm"