#!/bin/bash
#
# Browser startup script for the Hardware Management Console and Support Element
#
# Description: Script used to run the browser as a low privledged user.
#
# Change log:
#
# 01/16/2006 Kurt Schroeder  -00 Initial creation
# 02/23/2006 Kurt Schroeder  -01 Re-extract home directory files if new TGZ detected
# 05/30/2006 Kurt Schroeder  -02 Fix home directory file permissions to adhere to security audits.
# 06/14/2006 Kurt Schroeder  -03 Alter Java plugin link on MCP4.
# 08/29/2006 Kurt Schroeder  -04 Add code to wait until X windows is ready (ipHMC).
# 08/30/2006 Jim Hennessy    -05 Handle different Firefox install locations
# 11/17/2006 Kurt Schroeder  -06 Change password expire time for browser userid.
# 12/12/2006 Kurt Schroeder  -07 Cleanup cache before starting the browser.
# 01/24/2007 Kurt Schroeder  -08 Add code to fix prefs.js before starting the browser.
# 08/21/2007 Kurt Schroeder  -09 Handle double byte input.

traceIt() {
   actzTrace "XTOMBRJF: $1"
}

traceCmd() {
   local rc=
   local msg=

   msg=`$1 2>&1`
   rc=$?
   traceIt "cmd results [$1;rc=$rc]: $msg"
   return $rc
}

tracePipe() {
   while read line;
   do
      traceIt "$line";
   done
}

#-07 start
#Fix the browser prefs.js file.
fix_prefs() {
   local parts= part1= part2= prefline= prefsfile=;
   #user_pref("intl.accept_languages", "en");

   parts=`echo "$2 " | sed -e 's/\..*$//1' -e 's/_/ /g' | tr '[:upper:]' '[:lower:]'`;
   part1=`echo "$parts" | cut --fields=1 '--delimiter= '`;
   part2=`echo "$parts" | cut --fields=2 '--delimiter= '`;

   langlist="en";
   if [ -n "$part1" ]; then
      #First part is not empty
      acceptlang="$part1";
      if [ -n "$part2" ]; then
         #Second part is not empty
         acceptlang="${acceptlang}-${part2}";
      fi
      if [ "$acceptlang" != "$langlist" ]; then
         langlist="${acceptlang},${langlist}";
      fi
   fi
   prefline="user_pref(\"intl.accept_languages\", \"$langlist\");";
   echo "prefline=[$prefline]";
   prefsfile=`find "$1/.mozilla/firefox" -name 'prefs.js' | sed -e 's/[[:blank:]].*$//1'`;
   echo "prefsfile=[$prefsfile]";
   if [ -n "$prefsfile" ]; then
      cat "$prefsfile" | sed -e "s/^.*user_pref(\"intl\.accept_languages\",.*$/${prefline}/1" > "$1/prefs.tmp"
      cp -v "$1/prefs.tmp" "$prefsfile";
      rm -v "$1/prefs.tmp";
   else
      echo "Could not find prefs.js file.";
   fi
}
#-07 end

#-05 start
# The getFirefoxLibDir function is derived from the version in the firefoxKiosk script
function getFirefoxLibDir() {
   # Find Firefox launching shell script
   local scriptName=$(which firefox)
   if [[ -z "$scriptName" ]]; then
      # Not in the PATH, apparently.  Check likely locations for driver machine
      set -- $(ls -d /usr/lib/firefox*)
      if [[ $# == 0 ]]; then
         set -- $(ls -d /opt/MozillaFirefox-*)
         if [[ $# == 0 ]]; then
            echo "Unable to deduce Firefox install dir.  Can't find a" >&2
            echo "firefox install under /usr/lib or /opt" >&2
            return

         elif [[ $# > 1 ]]; then
            echo "Unable to deduce Firefox install dir.  More than one" >&2
            echo "version seems to be installed under /opt" >&2
            return
         fi

      elif [[ $# > 1 ]]; then
         echo "Unable to deduce Firefox install dir.  More than one" >&2
         echo "version seems to be installed under /usr/lib" >&2
         return
      fi

      local scriptNamePossibilies="$1/bin/firefox.sh $1/firefox.sh $1/bin/firefox $1/firefox"
      local scriptNameTest
      for scriptNameTest in $scriptNamePossibilies; do
         if [[ -r "$scriptNameTest" ]]; then
            scriptName="$scriptNameTest"
            break
         fi
      done

      if [[ ! -r "$scriptName" ]]; then
         echo "Can't find Firefox launcher file: $scriptName" >&2
         return
      fi
   fi

   # We know the script name.  Find the install dir.
   local libDir=$(cat "$scriptName"|grep 'MOZ_DIST_LIB='|sed -r -e 's/MOZ_DIST_LIB="(.*)"\s*/\1/')
   if [[ -z "$libDir" ]]; then
      libDir=$(cat "$scriptName"|grep 'MOZ_DIST_BIN='|sed -r -e 's/MOZ_DIST_BIN="(.*)"\s*/\1/')
   fi

   [[ -n "$libDir" && -e "$libDir/chrome/browser.jar" ]] && echo "$libDir"
}
#-05 end

traceIt "browserjail script called with: $*"
lang=$1
shift 1

# Get common function definitions
. ${CONSOLE_PATH}hmcfunctions

# A function to check to see if a group with a specified name exists
# Arguments:
# . The group name to check
# Returns a non-empty string if the group exists; otherwise, returns an empty string
checkgroup() {
   echo `cat /etc/group | sed -e /$1:/!D`
}

# Userid/group for running the browser.
userid="browser"
group="browser"

# Make sure the userid/group exist and have the correct settings.
if [ -z "`checkgroup $group`" ]; then
   # The group does not exists, so create it.
   traceIt "Group does not exist, so creating it..."
   groupadd "$group" 2>&1 | tracePipe
fi
if [ -z "`checkuser $userid`" ]; then
   # The user does not exist, so create it.
   traceIt "User does not exist so creating it..."
   useradd -c "Browser Userid" -g "$group" -d "/home/$userid" -M "$userid" 2>&1 | tracePipe
else
   # The userid already exists.
   traceIt "User already exits, so only modifying it..."
   usermod -c "Browser Userid" -g "$group" -d "/home/$userid" "$userid" 2>&1 | tracePipe
fi
#-06 start
# Make sure browser userid's password does not expire anytime soon.
passwd -x 99999 "$userid" 2>&1 | tracePipe
#-06 end

# Make sure the user's home directory has only what we want in it.
if [ ! -d "/home/$userid" ]; then
   traceIt "Creating user's home directory: /home/$userid"
   mkdir -p "/home/$userid"
   tar -xzf "${CONSOLE_PATH}hmcmanager.tgz" -C "/home/$userid" 2>&1 | tracePipe
   find "/home/$userid" -type f -name secmod.db | xargs rm -fv 2>&1 | tracePipe
   touch -r "${CONSOLE_PATH}hmcmanager.tgz" "/home/$userid/hmcmanager.loaded" 2>&1 | tracePipe
else
   if [ "${CONSOLE_PATH}hmcmanager.tgz" -nt "/home/$userid/hmcmanager.loaded" ]; then
      traceIt "Re-extracting all files in user's home directory, since hmcmanager.loaded not found or is old"
      tar -xzf "${CONSOLE_PATH}hmcmanager.tgz" -C "/home/$userid" 2>&1 | tracePipe
      touch -r "${CONSOLE_PATH}hmcmanager.tgz" "/home/$userid/hmcmanager.loaded" 2>&1 | tracePipe
   else
      traceIt "Replacing any missing files in user's home directory..."
      tar -xkzf "${CONSOLE_PATH}hmcmanager.tgz" -C "/home/$userid" 2>&1 | tracePipe
   fi
fi
traceIt "Removing any unwanted files..."
find "/home/$userid" -mindepth 1 -maxdepth 1 -type f | sed -e '/\/\.java\.policy/D' -e '/\/hmcmanager.loaded/D' | xargs rm -fv 2>&1 | tracePipe
traceIt "Removing any unwanted directories..."
find "/home/$userid" -mindepth 1 -maxdepth 1 -type d | sed -e '/\/\.acrobat$/D' -e '/\/\.mozilla$/D' | xargs rm -frv 2>&1 | tracePipe
traceIt "Removing any 'lock' files..."
find "/home/$userid/.mozilla" -name lock | xargs rm -fv 2>&1 | tracePipe
traceIt "Removing any 'cache' directories..."
find "/home/$userid/.mozilla" -name Cache -type d | xargs rm -frv 2>&1 | tracePipe
echo -e '# .bashrc\numask 002' > "/home/$userid/.bashrc"
traceIt "Setting ownership of all files/directories in user's home directory"
chown -R "$userid:$group" "/home/$userid"

#-02 start
chmod -v 'u=rwx,g=r,o=' "/home/$userid" 2>&1 | tracePipe
chmod -v -R 'o=' "/home/$userid" 2>&1 | tracePipe
find "/home/$userid" -type f | xargs -r chmod -v 'g-w' 2>&1 | tracePipe
#-02 end

# Make sure the user has a useful place on /ffdc to save files from the browser.
downloadFolder="/ffdc/browser"
if [ ! -d "$downloadFolder" ]; then
   traceIt "Creating user's download directory..."
   mkdir "$downloadFolder"
fi
chown "${userid}:nobody" "$downloadFolder"
chmod g+s "$downloadFolder"

#-03 start
if [ -d "/sys/block" ]; then
   traceIt "it looks like MCP4, so check the java plugin..."

   #-05 start
   # Figure out where Firefox is installed.
   firefoxLib=$(getFirefoxLibDir)
   if [[ -z "$firefoxLib" ]]; then
      traceIt "Unable to deduce location of Firefox package."
   else
      if [ ! -e "$firefoxLib/plugins/libjavaplugin_oji.so" ]; then
         traceIt "Need to create the java plugin link."
         ln -vs "/java/jre/bin/libjavaplugin_ojigcc3.so" "$firefoxLib/plugins/libjavaplugin_oji.so" 2>&1 | tracePipe
      else
         traceIt "java plugin link already exists."
      fi
   fi
   #-05 end
fi
#-03 end

#-04 start
# Make sure X windows is ready
xrc="1";
while [ "$xrc" != "0" ]; do
   DISPLAY=127.0.0.1:0 xset -q >/dev/null;
   xrc="$?";
   if [ "$xrc" != 0 ]; then
     traceIt "X windows is not ready yet; waiting a little while for it";
     sleep 5s;
   else
      traceIt "X windows is ready; lets see if fluxbox is running";
      if ps -eo cmd | sed -e 's/ .*$//1' | grep -q fluxbox; then
         traceIt "fluxbox is running; so we are all set to start the browser";
         xrc="0";
      else
         traceIt "fluxbox is not running; waiting a little while for it";
         sleep 5s;
         xrc="1";
      fi
   fi
done
#-04 end

#-05 start
fix_prefs "/home/$userid" "$lang" | tracePipe
#-05 end

# Run the browser under this special userid
traceIt "Starting the browser with \"[$*]\""
xmodifiers=$(grep 'export XMODIFIERS' /etc/SuSEconfig/profile|awk '{print $2}')
traceIt "xmodifiers=$xmodifiers"
su - "$userid" --command="LANG=$lang $xmodifiers DISPLAY=127.0.0.1:0 $* -a Driver" 2>&1 | tracePipe
# Add the env var NSPR_LOG_MODULES=all:5 to the command above to activate
# all internal Firefox tracing.  Beware it substantially slows down the
# browser.  It runs a lot quicker if you change "tracePipe" to
#   tracepipe -a -b /var/log/firefox.log.bak -m 1048576 /var/log/firefox.log
