#!/bin/sh
#
# ident "@(#)$Id: kioskautologinuser.sh 446 2012-07-02 20:08:44Z jbarfurt $ Oracle"
#
# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
#

# Autologin script for kiosk under gdm
#
# To configure for use, change GDM configuration (custom.conf) to contain
# the following settings:
#
# daemon/AutomaticLoginEnable=true
# daemon/AutomaticLogin=/opt/SUNWkio/lib/gdm/kioskautologinuser| 
#
# Alternatively this script can be chained from other autologin scripts
#

theModule=kiosk:gdm:kioskautologinuser

#
## main
#

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

KIOSK_USERALLOC=$KIOSK_LIB_DIR/kioskuseralloc
KIOSK_PREPSESSION=$KIOSK_LIB_DIR/prepsession

errfile=`mktemp /tmp/kioskuseralloc-XXXXXX.$$.err`

username=`$KIOSK_USERALLOC 2> $errfile`
ret=$?

reason="disabled"
if [ $ret -ne 0 ] ; then
 logError -m $theModule -l "Allocating kiosk user: `cat $errfile`"
 reason="allocation error"
fi
rm -f $errfile

if [ -z "$username" ] ; then 
 logDebug -m $theModule \
	  -l "No kiosk user allocated on display $DISPLAY: $reason"
 exit 1
fi

logDebug -m $theModule \
      -l "(Re)allocated kiosk user $username on display $DISPLAY"

if ${RUNNING_UNDER_GDM:-false} ; then 
 svc="gdm-autologin"
 logDebug -m $theModule -l "Detected GDM"
else
 # This is unexpected, so we don't have a pam svc to simulate
 # Still continuing (for debugging etc)
 svc="unknown-autologin"
 logDebug -m $theModule -l "Unknown DM context"
fi

# Preliminary user setup, so DM treats user as valid 
usergroup=`/usr/bin/id -gn "$username"`
userhome=`getent passwd $username | awk -F: '{ print $6 }'`

env USER="$username" GROUP="$usergroup" HOME="$userhome" \
	KIOSK_PAM_SERVICE="$svc" \
	$KIOSK_PREPSESSION
ret2=$?
if [ $ret2 -ne 0 ] ; then
 logWarning -m $theModule -l "Failed to prepare session for $username: DM may behave unexpectedly"
 # XXX: Rollback here? (finishsession, kioskuserclear) - probably not
fi

echo "$username"
exit $ret
