#!/bin/sh
#
# ident "@(#)$Id: initsession.sh 447 2012-08-22 16:09:00Z jbarfurt $ Oracle"
#
# Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
#

theModule=kiosk:initsession

#
## Some functions used to ensure that the Kiosk Session Starter,
## /opt/SUNWkio/lib/Xsession is invoked by the current login manager.
##
## login manager specific mechanisms are used to make this happen correctly.
## pam_kiosk makes the pam service name available as an environment variable,
## KIOSK_PAM_SERVICE. We use this name to identify which login manager
## specific mechanism should be used to setup the Kiosk Seession Starter.
##
setSessionStarter()
{
 case "$KIOSK_PAM_SERVICE" in
  dtlogin*)
  	setDTLOGINSessionStarter
	;;
  gdm*)    
  	initGDM
  	setGDMSessionStarter &&
	setGDMCacheFile &&
	checkGDMDesktopFile
	;;
  *)
  	logError -m $theModule -l "Error: Unknown pam service '$KIOSK_PAM_SERVICE'"
     	return $KIOSK_RESULT_FAILED
	;;
 esac
}

#
## Some functions used to ensure that the Kiosk Session Starter,
## is seen as preconfigured by the current login manager,
## so that it doesn't start showing session selection UI.
##
## login manager specific mechanisms are used to make this happen correctly.
## The caller makes the expected pam service name available as an environment 
## variable, KIOSK_PAM_SERVICE. We use this name to identify which login
## manager specific mechanism should be used.
##
## (Needed for the new GDM, especially autologin)
## 
setSessionStarterEnv()
{
 case "$KIOSK_PAM_SERVICE" in
  gdm*)    
  	initGDM
  	logDebug -m $theModule -l "Preparing GDM environment"
	setGDMCacheFile  && checkGDMDesktopFile
	;;
  *)
  	logDebug -m $theModule -l "Nothing to do for service '$KIOSK_PAM_SERVICE'"
	;;
 esac
}

# Set variables for GDM support
initGDM()
{
    # This may point to a real desktop file, if installed (e.g. "kiosk" -> kiosk.desktop)
    # Fallback is the 'custom' session, which should need no desktop file and relies on the
    # $HOME/.xsession we set up
    KIO_GDM_SESSION=${KIOSK_SESSION_DESKTOP_NAME:-custom}
}

makeGDMdmrc() 
{
 _theGDMdmrc="$1"
 getSessionLanguage
 rm -f "$_theGDMdmrc"
 cat <<- ! > "$_theGDMdmrc"
	[Desktop]
	Session=$KIO_GDM_SESSION
	Language=$SESSION_LANGUAGE
	!
 if [ $? -ne 0 ] ; then
  logError -m $theModule -l "Error: failed to create file '$_theGDMdmrc'"
  return $KIOSK_RESULT_FAILED
 fi
 logDebug -m $theModule -l "Created dmrc file '$_theGDMdmrc'"

 chown $USER:$GROUP "$_theGDMdmrc"
 if [ $? -ne 0 ] ; then
  logInfo -m $theModule \
  	-l "Notice: failed to set ownership of file '$_theGDMdmrc'"
 fi
 return $KIOSK_RESULT_SUCCESS
}

setGDMSessionStarter()
{
 _theDMRCFile=$HOME/.dmrc
 _theXsessionFile=$HOME/.xsession

 #
 ## First create the .dmrc file
 #
 # Note: There is no real security reason for not allowing this file to 
 #       be world readable in our case. Thus deferring the chmod from
 #       644 (see umask setting in main) to 600 is safe.
 #
 makeGDMdmrc "$_theDMRCFile"
 if [ $? -ne 0 ] ; then
  return $KIOSK_RESULT_FAILED
 fi

 # Change to mode gdm wants to see(?)
 chmod 600 $_theDMRCFile
 if [ $? -ne 0 ] ; then
  logInfo -m $theModule -l "Notice: failed to chmod file '$_theDMRCFile'"
  return $KIOSK_RESULT_FAILED
 fi

 ## Next create the .xsession file
 #
 rm -f $_theXsessionFile && \
 	echo $KIOSK_PREFIX/lib/Xsession > $_theXsessionFile
 if [ $? -ne 0 ] ; then
  logError -m $theModule -l "Error: failed to create file '$_theXsessionFile'"
  return $KIOSK_RESULT_FAILED
 fi

 chmod 744 $_theXsessionFile
 if [ $? -ne 0 ] ; then
  logError -m $theModule -l "Error: failed to chmod file '$_theXsessionFile'"
  return $KIOSK_RESULT_FAILED
 fi

 chown $USER:$GROUP $_theXsessionFile
 if [ $? -ne 0 ] ; then
  logError -m $theModule \
           -l "Error: failed to chown $_theXsessionFile"
  return $KIOSK_RESULT_FAILED
 fi

 return $KIOSK_RESULT_SUCCESS
}

setGDMCacheFile()
{
 _theCacheDir=/var/cache/gdm
 _theUserCacheDir=$_theCacheDir/$USER
 _theDMRCCacheFile=$_theUserCacheDir/dmrc

 # Now create the cached copy, if needed
 if [ -d "$_theCacheDir" ] ; then
  if [ ! -d "$_theUserCacheDir" ] ; then 
   mkdir -m755 "$_theUserCacheDir"
   if [ $? -ne 0 ] ; then
    logError -m $theModule \
    	-l "Error: failed to make directory $_theUserCacheDir"
    return $KIOSK_RESULT_FAILED
   fi
   chown $USER:$GROUP "$_theUserCacheDir"
   if [ $? -ne 0 ] ; then
    logInfo -m $theModule \
    	-l "Notice: failed to chown directory $_theUserCacheDir"
   fi
  fi
  makeGDMdmrc "$_theDMRCCacheFile"
  if [ $? -ne 0 ] ; then
   return $KIOSK_RESULT_FAILED
  fi
 fi
}

checkGDMDesktopFile()
{
 # Only do this for new gdm (?)
 if isOldGDM ; then
  return 0
 fi
 # Nothing to do for the built-in 'custom' session type
 if [ "$KIO_GDM_SESSION" = "custom" ] ;then
  return 0
 fi
 # Files where GDM looks for session desktop files
 _theSessionDesktopDirs="/etc/X11/sessions
	/etc/dm/Sessions
	/usr/share/xsessions
	/usr/share/gdm/BuiltInSessions"
 
 for sdDir in $_theSessionDesktopDirs ; do 
  if [ -s "$sdDir/$KIO_GDM_SESSION.desktop" ] ; then
    logDebug -m $theModule \
    	-l "Found $KIO_GDM_SESSION session at $sdDir/$KIO_GDM_SESSION.desktop"
   return 0
  fi
 done

 # Should we try to create/link our xxx.desktop here?
 # Who would clean that up?
 logWarning -m $theModule -l "Error: no $KIO_GDM_SESSION.desktop file found."
 return $KIOSK_RESULT_FAILURE
}

setDTLOGINSessionStarter()
{
 _theDtDir=$HOME/.dt
 _theSessionDir=$_theDtDir/sessions
 _theLastSessionFile=$_theSessionDir/lastsession

 #
 ## First create the dtlogin sessions directory
 #
 mkdir -p $_theSessionDir
 if [ $? -ne 0 ] ; then
  logError -m $theModule \
           -l "Error: failed to create directory '$HOME/.dt/sessions'"
  return $KIOSK_RESULT_FAILED
 fi
 chmod 755 $_theDtDir $_theSessionDir
 if [ $? -ne 0 ] ; then
  logError -m $theModule \
           -l "Error: failed to chmod $_theDtDir or $_theSessionDir"
  return $KIOSK_RESULT_FAILED
 fi

 #
 ## Next create the lastsession file
 #
 echo "$KIOSK_PREFIX/lib/Xsession\c" > $_theLastSessionFile
 if [ $? -ne 0 ] ; then
  logError -m $theModule \
           -l "Error: failed to create file '$_theLastSessionFile'"
  return $KIOSK_RESULT_FAILED
 fi
 chmod 644 $_theLastSessionFile
 if [ $? -ne 0 ] ; then
  logError -m $theModule \
           -l "Error: failed to chmod file '$_theLastSessionFile'"
  return $KIOSK_RESULT_FAILED
 fi

 #
 ## Finally ensure correct ownership of all of the above
 #
 chown $USER:$GROUP $_theDtDir $_theSessionDir $_theLastSessionFile
 if [ $? -ne 0 ] ; then
  logError -m $theModule \
           -l "Error: failed to chown $_theDtDir, $_theSessionDir or $_theLastSessionFile"
  return $KIOSK_RESULT_FAILED
 fi

 return $KIOSK_RESULT_SUCCESS
}

# Helper functions to load locale setting
loadSessionLanguage()
{
 if [ -n "$KIOSK_SESSION_EXEC" ] ; then
  # Configuration was already loaded
  return 0
 fi
 # We know that DISPLAY, USER and HOME are set
 logDebug -m "$theModule" \
          -l "loading session language for $USER at $DISPLAY"

 # We assume that configuration hasn't been activated, so we use
 # the static configuration for the display
 _paramopts="-s $DISPLAY -x -e USER -e HOME -e DISPLAY"
 KIOSK_SESSION_LOCALE=`$KIOSK_BIN_DIR/kioskparam $_paramopts -k KIOSK_SESSION_LOCALE`
 if [ $? -ne 0 ] ; then
  logDebug -m $theModule \
           -l "Non-Fatal Error: failed to load KIOSK_SESSION_LOCALE from configuration"
	   return 1
 fi
 return 0
}

# Extract a locale value from the system environment
getEnvLocale()
{
 _localeSettings=`/usr/bin/locale`
 _facet="$1"
 sh -c "eval $_localeSettings  ; echo \$$_facet"
}

getSessionLanguage() 
{
 if [ -n "$SESSION_LANGUAGE" ]  ; then
  return
 fi
 loadSessionLanguage
 if [ -n "$KIOSK_SESSION_LOCALE" ] ; then
  logDebug -m theModule -l "Using configured session locale $KIOSK_SESSION_LOCALE"
  SESSION_LANGUAGE="$KIOSK_SESSION_LOCALE"
  return
 fi
 if [ -n "$LANG" ] ; then
  logDebug -m theModule -l "Using locale  from LANG=$LANG"
  SESSION_LANGUAGE="$LANG"
  return
 fi
 SESSION_LANGUAGE=`getEnvLocale LC_MESSAGES`
 if [ -n "$SESSION_LANGUAGE" ] ; then
  logDebug -m theModule -l "Using LC_MESSAGES locale: $SESSION_LANGUAGE"
 else
  SESSION_LANGUAGE="en_US.UTF-8"
  logDebug -m theModule -l "Using fallback locale: $SESSION_LANGUAGE"
 fi
}


#
## The limited preparation sequence of events is
##
## 1. load the Kiosk common utils /opt/SUNWkio/lib/utils.sh (done in main)
## 2. ensure the environment is sane (done in main)
## 3. do a full cleanup for the user (to ensure no stale data interferes)
## 4. setup the global environment for the Kiosk Session Starter
#
prepare_user_session() 
{
 #
 ## Ensure we have a sane environment
 #
 if [ -z "$KIOSK_PAM_SERVICE" -o -z "$DISPLAY" -o \
      -z "$USER" -o -z "$GROUP" -o -z "$HOME" ] ; then
  logError -m $theModule \
	   -l "Error: \$KIOSK_PAM_SERVICE, \$DISPLAY, \$USER, \$GROUP or \$HOME not specified"
  logDebug -m $theModule -l "Environment: `env`"
  exit $KIOSK_RESULT_FAILED
 fi

 #
 ## Do a cleanup for the user before proceeding
 #
 cleanup $theModule $USER "$HOME"
 if [ $? -ne $KIOSK_RESULT_SUCCESS ] ; then
  logInfo -m $theModule \
	   -l "Notice: failed to clean up for session prep for user '$USER'"
 fi

 #
 ## Setup the Kiosk Session Starter Environment
 #
 setSessionStarterEnv
 if [ $? -ne $KIOSK_RESULT_SUCCESS ] ; then
  logError -m $theModule -l "Error: failed to set session starter environment"
  exit $KIOSK_RESULT_FAILED
 fi

 logDebug -m $theModule \
	  -l "Success: Prelininary Kiosk session setup complete for display '$DISPLAY'"
 exit $KIOSK_RESULT_SUCCESS
}

#
## The full sequence of events is
##
## 1. load the Kiosk common utils /opt/SUNWkio/lib/utils.sh (done in main)
## 2. ensure the environment is sane (done in main)
## 3. do a full cleanup for the user
## 4. activate and load kiosk session configuration
## 5. create the user home directory and install the user prototype
## 6. install the primary session prototype
## 7. execute the primary session pre-session script if configured
## 8. setup the Kiosk Session Starter
## 9. start the Critical Applications Monitor
#
full_init_session() 
{
 #
 ## Ensure we have a sane environment
 #
 if [ -z "$KIOSK_PAM_SERVICE" -o -z "$DISPLAY" -o -z "$USER" -o \
      -z "$GROUP" -o -z "$HOME" -o -z "$KIOSK_PROTOTYPE" ] ; then
  logError -m $theModule \
	   -l "Error: \$KIOSK_PAM_SERVICE, \$DISPLAY, \$USER, \$GROUP, \$DISPLAY or \$KIOSK_PROTOTYPE not specified"
  exit $KIOSK_RESULT_FAILED
 fi

 #
 ## Do a cleanup for the user before proceeding
 #
 cleanup $theModule $USER "$HOME"
 if [ $? -ne $KIOSK_RESULT_SUCCESS ] ; then
  logError -m $theModule \
	   -l "Error: failed to clean up after previous Kiosk session for user '$USER'"
  exit $KIOSK_RESULT_FAILED
 fi

 #
 ## Create the dynamic data and user home directories
 #
 makeDynDir $theModule $USER
 if [ $? -ne $KIOSK_RESULT_SUCCESS ] ; then
  logError -m $theModule \
	   -l "Error: failed to create dynamic data directory for user '$USER'"
  exit $KIOSK_RESULT_FAILED
 fi

 createHome $theModule $USER $GROUP "$HOME" "$KIOSK_PROTOTYPE"
 if [ $? -ne $KIOSK_RESULT_SUCCESS ] ; then
  logError -m $theModule \
	   -l "Error: failed to set up home directory '$HOME' for user '$USER'"
  cleanup $theModule $USER "$HOME"
  exit $KIOSK_RESULT_FAILED
 fi

 #
 # Install and load session configuration
 #
 activateSessionConfiguration $theModule $USER $DISPLAY
 if [ $? -ne $KIOSK_RESULT_SUCCESS ] ; then
  logError -m $theModule -l "Error: failed to set up session configuration"
  cleanup $theModule $USER "$HOME"
  exit $KIOSK_RESULT_FAILED
 fi

 loadSessionConfiguration $theModule 
 if [ $? -ne $KIOSK_RESULT_SUCCESS ] ; then
  logError -m $theModule -l "Error: failed to load Session Descriptor"
  cleanup $theModule $USER "$HOME"
  exit $KIOSK_RESULT_FAILED
 fi

 #
 # Basic sanity test
 #
 if [ ! -s "$KIOSK_SESSION_EXEC" ] ; then
  logError -m $theModule -l "Error: session executable '$KIOSK_SESSION_EXEC' not found or empty."
  cleanup $theModule $USER "$HOME"
  exit $KIOSK_RESULT_FAILED
 fi

 #
 ## Install primary session prototype
 #
 if [ ! -z "$KIOSK_SESSION_PROTOTYPE" ] ; then
  installPrototype $theModule "$KIOSK_SESSION_PROTOTYPE" $HOME $USER $GROUP
  if [ $? -ne $KIOSK_RESULT_SUCCESS ] ; then
   logError -m $theModule -l "Error: failed to install session prototype"
   cleanup $theModule $USER "$HOME"
   exit $KIOSK_RESULT_FAILED
  fi
 fi

 #
 ## Execute primary session pre-session script, if specified
 #
 if [ ! -z "$KIOSK_SESSION_PRE" ] ; then
  if [ ! -x "$KIOSK_SESSION_PRE" ] ; then
   logError -m $theModule \
	    -l "Error: session pre-session script '$KIOSK_SESSION_PRE' is not executable"
   cleanup $theModule $USER "$HOME"
   exit $KIOSK_RESULT_FAILED
  fi
  "$KIOSK_SESSION_PRE"
  if [ $? -ne 0 ] ; then
   logError -m $theModule \
	    -l "Error: session pre-session script '$KIOSK_SESSION_PRE' failed"
   cleanup $theModule $USER "$HOME"
   exit $KIOSK_RESULT_FAILED
  fi
 fi

 #
 ## Setup the Kiosk Session Starter
 #
 setSessionStarter
 if [ $? -ne $KIOSK_RESULT_SUCCESS ] ; then
  logError -m $theModule -l "Error: failed to set correct session starter"
  cleanup $theModule $USER "$HOME"
  exit $KIOSK_RESULT_FAILED
 fi

 #
 ## Start critical applications monitor
 #
 startCriticalAppsMonitor $theModule
 if [ $? -ne $KIOSK_RESULT_SUCCESS ] ; then
  logError -m $theModule \
	   -l "Error: failed to start Critical Applications Monitor"
  cleanup $theModule $USER "$HOME"
  exit $KIOSK_RESULT_FAILED
 fi

 logDebug -m $theModule \
	  -l "Success: Kiosk session setup complete for display '$DISPLAY'"
 exit $KIOSK_RESULT_SUCCESS
}

#
##
## Main
##
# set up preliminary priorities for error logging
log_err_prio=${KIOSK_LOG_FACILITY:-user}.${KIOSK_LOGPRI_ERROR:-error}
log_dbg_prio=${KIOSK_LOG_FACILITY:-user}.debug

logger -i -p $log_dbg_prio -t $theModule "setting up Kiosk session"

#
## Load utilities and setup basic Kiosk Environment
#
theUtilsFile=/opt/SUNWkio/lib/utils.sh
if [ ! -r $theUtilsFile ] ; then
 logger -i -p $log_err_prio -t $theModule \
        "Error: can't read Kiosk utils file '$theUtilsFile'"
 exit 1
else
 . $theUtilsFile
 if [ $? -ne 0 ] ; then
  logger -i -p $log_err_prio $theModule \
         "Error: failed to load Kiosk utils file '$theUtilsFile'"
  exit 1
 fi 
fi

#
## 6831388 Ensure sane file permissions regardless of global umask
#
umask 022

#
## Check options and run main function
##
## Available options:
##
## -p Do system level preparation, but don't build the full session environment
##
#
## As long as we have only one option, we don't bother with getopts parsing
#
if [ $# -ge 1 ] && [ "x$1" = "x-p" ] ; then
 theModule=kiosk:initsession:prep
 logger -i -p $log_dbg_prio -t $theModule "running in preparation mode"
 shift 
 prepare_user_session "$@"
else
 full_init_session "$@"
fi 


