#!/bin/ksh -p
#
# ident "@(#)utgdmconfigctl.ksh	1.28	12/09/24 Oracle"
#
# Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
#

set -u
########################################################################
#
# Configures gdm custom.conf to set properties for Sun Ray
#
# Further creates 0010.SUNWut.xdmEnv.sh and 0100.SUNWut.sh links
# if any other gdm than our own is installed
#
########################################################################

function errout {
	print -u2 "utgdmconfigctl $@"
}

function updateOldGdmValue {
	gdmflexiserver --command="UPDATE_CONFIG daemon/$1" >/dev/null
}

# updateOldGdmCustom
function updateOldGdmCustom {
	${AWK} -F= -v GDMGREETER=$GDMGREETER -v KIOSKGREETER="$KIOSKGREETER" \
		-v BASEXSESSION=$BASEXSESSION -v SRSAUTOLOGIN="$SUNRAY_AUTOLOGIN" \
		-v SUNWUTBegin="$SUNWUTBegin" -v SUNWUTEnd="$SUNWUTEnd" \
		-v SRCRASHSCRIPT=$SRCRASHSCRIPT '
		BEGIN {
			FoundVT=0;
			FoundDy=0;
			FoundReboot=0;
			FoundHalt=0;
			FoundCrash=0;
			if (BASEXSESSION == "")
				FoundBx=1;
			else
				FoundBx=0;
			if (KIOSKGREETER == "")
				FoundGt=1;
			else
				FoundGt=0;
			if (SRSAUTOLOGIN == "") {
				FoundAl=1;
				FoundAle=1;
			}
			else {
				FoundAl=0;
				FoundAle=0;
			}
			InDaemonSection=0;
		}
		/\[daemon\]/ {
			InDaemonSection=1;
			print;
			next;
		}
		$1 == "VTAllocation" {
			FoundVT=1;
			if ($2 !~ "false.*") {
				print "# SUNRAY DEL " $0;
				print SUNWUTBegin;
				print "VTAllocation=false";
				print SUNWUTEnd;
				next;
			}
		}
		$1 == "DynamicXServers" {
			FoundDy=1;
			if ($2 !~ "true.*") {
				print "# SUNRAY DEL " $0;
				print SUNWUTBegin;
				print "DynamicXServers=true";
				print SUNWUTEnd;
				next;
			}
		}
		( KIOSKGREETER != "" ) && ( $1 == "Greeter" ) {
			FoundGt=1;
			if ($2 !~ (KIOSKGREETER ".*/gdmgreeter")) {
				print "# SUNRAY DEL " $0;
				print SUNWUTBegin;
				print "Greeter=" KIOSKGREETER GDMGREETER;
				print SUNWUTEnd;
				next;
			}
		}
		$1 == "RebootCommand" {
			FoundReboot=1;
			if ($2 != "") {
				print "# SUNRAY DEL " $0;
				print SUNWUTBegin;
				print "RebootCommand=";
				print SUNWUTEnd;
				next;
			}
		}
		$1 == "HaltCommand" {
			FoundHalt=1;
			if ($2 != "") {
				print "# SUNRAY DEL " $0;
				print SUNWUTBegin;
				print "HaltCommand=";
				print SUNWUTEnd;
				next;
			}
		}
		$1 == "XKeepsCrashing" {
			FoundCrash=1;
			if ($2 != "") {
				print "# SUNRAY DEL " $0;
				print SUNWUTBegin;
				print "XKeepsCrashing=" SRCRASHSCRIPT;
				print SUNWUTEnd;
				next;
			}
		}
		(BASEXSESSION != "") && ($1 == "BaseXsession") {
			FoundBx=1;
			if ($2 !~ BASEXSESSION ".*") {
				print "# SUNRAY DEL " $0;
				print SUNWUTBegin;
				print "BaseXsession=" BASEXSESSION;
				print SUNWUTEnd;
				next;
			}
		}
		(SRSAUTOLOGIN != "") && ($1 == "AutomaticLogin") {
			FoundAl=1;
			if ($2 != "") {
				print "# SUNRAY DEL " $0;
				print SUNWUTBegin;
				print "AutomaticLogin=" SRSAUTOLOGIN "|";
				print SUNWUTEnd;
				next;
			}
		}
		(SRSAUTOLOGIN != "") && ($1 == "AutomaticLoginEnable") {
			FoundAle=1;
			if ($2 != "") {
				print "# SUNRAY DEL " $0;
				print SUNWUTBegin;
				print "AutomaticLoginEnable=true";
				print SUNWUTEnd;
				next;
			}
		}
		InDaemonSection && /\[.*\]/ {
			# we have hit the end of the [daemon] block
			if ( ! FoundVT \
			     || ! FoundDy \
			     || ! FoundGt \
			     || ! FoundAl \
			     || ! FoundAle \
			     || ! FoundBx \
			     || ! FoundReboot \
			     || ! FoundHalt \
			     || ! FoundCrash) {
				print SUNWUTBegin;
				if (! FoundVT) {
					print "VTAllocation=false";
					FoundVT=1
				}
				if (! FoundDy) {
					print "DynamicXServers=true";
					FoundDy=1;
				}
				if (! FoundGt) {
					print "Greeter=" KIOSKGREETER GDMGREETER;
					FoundGt=1;
				}
				if (! FoundBx) {
					print "BaseXsession=" BASEXSESSION;
					FoundBx=1;
				}
				if (! FoundReboot) {
					print "RebootCommand=";
					FoundReboot=1;
				}
				if (! FoundHalt) {
					print "HaltCommand=";
					FoundHalt=1;
				}
				if (! FoundCrash) {
					print "XKeepsCrashing=" SRCRASHSCRIPT;
					FoundCrash=1;
				}
				if (! FoundAl) {
					print "AutomaticLogin=" SRSAUTOLOGIN "|";
					FoundAl=1;
				}
				if (! FoundAle) {
					print "AutomaticLoginEnable=true";
					FoundAle=1;
				}
				print SUNWUTEnd;
			}
			InDaemonSection=0;
		}
		{
			print $0;
		}
		END { 
			# Similar to "end of the [daemon] block" case above, but
			# no block follows - daemon was last, or missing
			if ( ! FoundVT \
			     || ! FoundDy \
			     || ! FoundGt \
			     || ! FoundAl \
			     || ! FoundAle \
			     || ! FoundBx \
			     || ! FoundReboot \
			     || ! FoundHalt) {
				print SUNWUTBegin;
				if (!InDaemonSection) {
					# daemon block was actually missing entirely
					print "[daemon]";
				}
				if (! FoundVT) {
					print "VTAllocation=false";
				}
				if (! FoundDy) {
					print "DynamicXServers=true";
				}
				if (! FoundGt) {
					print "Greeter=" KIOSKGREETER GDMGREETER;
				}
				if (! FoundBx) {
					print "BaseXsession=" BASEXSESSION;
				}
				if (! FoundReboot) {
					print "RebootCommand=";
				}
				if (! FoundHalt) {
					print "HaltCommand=";
				}
				if (! FoundCrash) {
					print "XKeepsCrashing=" SRCRASHSCRIPT;
				}
				if (! FoundAl) {
					print "AutomaticLogin=" SRSAUTOLOGIN "|";
					FoundAl=1;
				}
				if (! FoundAle) {
					print "AutomaticLoginEnable=true";
					FoundAle=1;
				}
				print SUNWUTEnd;
			}
		}
	' $1 
}

# updateNewGdmCustom
function updateNewGdmCustom {
	# Nothing to manipulate, if no autologin requested
	if [[ -z "$SUNRAY_AUTOLOGIN" ]] ; then
		cat $1
		return
	fi
	${AWK} -F= -v SRSAUTOLOGIN="$SUNRAY_AUTOLOGIN" \
		-v SUNWUTBegin="$SUNWUTBegin" -v SUNWUTEnd="$SUNWUTEnd"  '
		BEGIN {
			if (SRSAUTOLOGIN == "") {
				FoundAl=1;
				FoundAle=1;
			}
			else {
				FoundAl=0;
				FoundAle=0;
			}
			InDaemonSection=0;
		}
		/\[daemon\]/ {
			InDaemonSection=1;
			print;
			next;
		}
		(SRSAUTOLOGIN != "") && ($1 == "AutomaticLogin") {
			FoundAl=1;
			if ($2 != "") {
				print "# SUNRAY DEL " $0;
				print SUNWUTBegin;
				print "AutomaticLogin=" SRSAUTOLOGIN "|";
				print SUNWUTEnd;
				next;
			}
		}
		(SRSAUTOLOGIN != "") && ($1 == "AutomaticLoginEnable") {
			FoundAle=1;
			if ($2 != "") {
				print "# SUNRAY DEL " $0;
				print SUNWUTBegin;
				print "AutomaticLoginEnable=true";
				print SUNWUTEnd;
				next;
			}
		}
		InDaemonSection && /\[.*\]/ {
			# we have hit the end of the [daemon] block
			if ( ! FoundAl || ! FoundAle ) {
				print SUNWUTBegin;
				if (! FoundAl) {
					print "AutomaticLogin=" SRSAUTOLOGIN "|";
					FoundAl=1;
				}
				if (! FoundAle) {
					print "AutomaticLoginEnable=true";
					FoundAle=1;
				}
				print SUNWUTEnd;
			}
			InDaemonSection=0;
		}
		{
			print $0;
		}
		END { 
			# Similar to "end of the [daemon] block" case above, but
			# no block follows - daemon was last, or missing
			if ( ! FoundAl || ! FoundAle ) {
				print SUNWUTBegin;
				if (!InDaemonSection) {
					# daemon block was actually missing entirely
					print "[daemon]";
				}
				if (! FoundAl) {
					print "AutomaticLogin=" SRSAUTOLOGIN "|";
					FoundAl=1;
				}
				if (! FoundAle) {
					print "AutomaticLoginEnable=true";
					FoundAle=1;
				}
				print SUNWUTEnd;
			}
		}
	' $1 
}

function updateOldGdmNow {
	updateOldGdmValue VTAllocation
	updateOldGdmValue DynamicXServers
	[[ -n "$KIOSKGREETER" ]] && updateOldGdmValue Greeter
	updateOldGdmValue BaseXsession
	updateOldGdmValue RebootCommand
	updateOldGdmValue HaltCommand
	updateOldGdmValue XKeepsCrashing
	if [[ -n "$SUNRAY_AUTOLOGIN" ]] ; then
	    updateOldGdmValue AutomaticLogin
	    updateOldGdmValue AutomaticLoginEnable
	fi
}

function updateNewGdmNow {
	# GDM (multiseat) reloads custom.conf settings on HUP
	pkill -HUP -x gdm-binary
}

# restoreGdmCustom
#
#
function restoreGdmCustom {
	if ! ${AWK} -v SUNWUTBegin="$SUNWUTBegin" -v SUNWUTEnd="$SUNWUTEnd" '
		BEGIN {
			InSUNWUTBlock=0;
		}
		
		$0 == SUNWUTBegin {
			InSUNWUTBlock=1;
			next;
		}

		$0 == SUNWUTEnd {
			InSUNWUTBlock=0;
			next;
		}

		InSUNWUTBlock {
			next;
		}
		
		/^# SUNRAY DEL / {
		  sub("# SUNRAY DEL *", "", $0)
		  print $0
		  next;
		}

		{
			print $0;
		}

		END {
			if (InSUNWUTBlock)
				exit 1
			else
				exit 0
		}
	' $1
	then
		logit "Error: [${PROG}] malformed $1"
	fi
}

doGdmUserlist()
{
        typeset ul_op=${1:-"NULL"}
	if isOldGDMEnabled ; then
		return 
	fi
	# Set up locations
	GDMGCONFMANDATORYDIR="/var/lib/gdm/.gconf.mandatory"
	GDMGCONFSRC="xml:readwrite:$GDMGCONFMANDATORYDIR"
	GDMUSERLISTKEY="/apps/gdm/simple-greeter/disable_user_list"

	if [[ ! -d "$GDMGCONFMANDATORYDIR" ]] ; then
		return 
	fi
	case "$ul_op" in
	"disable")
		$GCONFTOOL --direct --config-source "$GDMGCONFSRC" --type bool --set "$GDMUSERLISTKEY" true
		;;
	"reset")
		$GCONFTOOL --direct --config-source "$GDMGCONFSRC" --unset "$GDMUSERLISTKEY"
		;;
	*)
		errout "Error: invalid user list operation requested: $ul_op"
		;;
	esac
}

function rmLink  {
	typeset LINK=$1
	if [ -L $LINK ] ; then
		rm -rf $LINK
		if $VERB; then
			print "$LINK is removed"
		fi
	fi
}

function mkLink  {

	typeset LINK_TO=$1
	typeset LINK=$2

	rm -rf $LINK
	ln -fs $LINK_TO $LINK
	if [ $? -ne 0 ]; then
		logit "Error: [${PROG}] Failed to create $LINK "
		return 1
	elif $VERB; then
		print "$LINK to $LINK_TO link made"
	fi
	return 0
}

function isSLES10 {
	if [ "$OS" != "SunOS" ] \
		&& [ -f /etc/SuSE-release ] \
		&& [ "`sed -n 's/^ *VERSION *= *\([0-9]*\).*/\1/p' /etc/SuSE-release`" = 10 ]; then
		return 0
	else
		return 1
	fi
}


########################################
# This function should return 0 iff this is a platform that execs the
# scripts in xinitrc.d, rather than sourcing them
########################################
function isPlatformExecing {
	isSLES10
}

function isOldGDMEnabled {
	test ! -x "$CK_Seat_Tool"
}

########################################################################
#
# Operation entry points, one for each keyword.	 This is where the
# specific work for this feature happens.
#
########################################################################


#
# disable()
#
function disable {
	typeset status=0

	if [ -n "$GDM_DIR" ]; then
		# The following code was imported from utinstall uninstallation
		for DIR in Init PreSession PostSession; do
			WDIR=${GDM_DIR}/${DIR}
			# Change the ksh field separator so that we
			# can iterate across the output of ls
			# line-by-line (i.e. file by file)
			OLDIFS="$IFS"
			IFS=@
			for DPYFILE in `ls ${WDIR}/* 2>/dev/null`; do
				if ls -l ${DPYFILE} | \
					grep SunRay >/dev/null 2>&1; then
					rm -f ${DPYFILE}
				fi
			done
			# Restore the ksh field separator
			IFS="$OLDIFS"
		done

		doGdmUserlist reset
		restoreGdmCustom $SYSTEM_CUSTOMCONF >> $TMPFILE 
		if [ $? != 0 ]; then
			logit "Error: GDM custom.conf cannot be restored correctly"
			logit "\tPlease inspect $SYSTEM_CUSTOMCONF manually"
			status=1
			rm $TMPFILE
		else
			mv $TMPFILE $SYSTEM_CUSTOMCONF
		# GDM needs to be restarted but system reboot is
		# required after uninstall so this will occur
		fi

		if $XINIT_SOURCES; then
			rmLink $SYSTEM_XINITRCD/0010.SUNWut.xdmEnv.sh 
			rmLink $SYSTEM_XINITRCD/0100.SUNWut.sh
		fi

		rm -f $SUNRAY_ETCDIR/xmgr
		rm -f $CK_display_file_target
	fi

	return $status
}

# workaround for bug 14607342
# DBus has a very low limit set for open file descriptors Since Linux
# has no way to affect running processes ulimits, We must instrument
# the DBus startup script during activation (utgdmconfigctl).  Problem
# is, DBus must then restart to pick up the change, and that hoses the
# console, which then must be restarted. Not friendly to console
# users.  We'll offer to restart at start of utsetup config, since it can be
# interactive, while activation code cannot.
function fixupDbus14607342 {
	if [[ ! -x /etc/init.d/messagebus ]]; then
		return 0
	fi
	typeset -i limit_want=16384

	typeset dbus_pid=$(pgrep -f "dbus-daemon --system")
	if [[ -z "$dbus_pid" ]]; then
	    errout "ERROR: No DBus daemon running"
	    return 0
	fi

	typeset -i limit_got=$(awk '/^Max open files/ {print $4}' /proc/$dbus_pid/limits)
	if [[ -z "$limit_got" ]]; then
	    errout "ERROR: can't determine current ulimits for DBus daemon"
	    return 1
	fi

	if (( "$limit_want" > "$limit_got" )); then
		typeset Tname=$(mktemp /var/opt/SUNWut/tmp/messagebus.$$.XXX)
		typeset ULine="ulimit -n 16384 # Sun Ray Software needs this"
		gawk -v ULine="$ULine" '
BEGIN { done = 0 }
$0 == ULine { next }
{ print }
done == 0 && /^[ 	]*$/ { printf("%s\n", ULine); done = 1 }
' /etc/init.d/messagebus > $Tname
		cp $Tname /etc/init.d/messagebus
		rm -f $Tname
		errout "ERROR: A reboot is required to allow the system"
		errout "DBus daemon to raise its file descriptor ulimit"
		# Reboot required, return status appropriately
		return 202
	fi
	return 0
}


#
# enable ()
#
function enable {
	typeset retstatus=0
	if [ -n "$GDM_DIR" ]; then
		if isOldGDMEnabled; then
			updateOldGdmCustom $SYSTEM_CUSTOMCONF >> $TMPFILE 
			mv $TMPFILE $SYSTEM_CUSTOMCONF
			updateOldGdmNow
		else
			doGdmUserlist disable
			updateNewGdmCustom $SYSTEM_CUSTOMCONF >> $TMPFILE 
			mv $TMPFILE $SYSTEM_CUSTOMCONF
			updateNewGdmNow
			fixupDbus14607342
			retstatus=$?
		fi
		
		if $XINIT_SOURCES && [ -d $SYSTEM_XINITRCD ]; then
			mkLink $SUNRAY_XINITRCD/0010.SUNWut.xdmEnv $SYSTEM_XINITRCD/0010.SUNWut.xdmEnv.sh
			mkLink $SUNRAY_XINITRCD/0100.SUNWut $SYSTEM_XINITRCD/0100.SUNWut.sh
		fi
		if [ -d $(dirname $CK_display_file_target) ]; then
			# This is GDM 2.22+, so link in our interface
			rm -f $CK_display_file_target
			ln -s $CK_display_file_src $CK_display_file_target
		fi
	fi

	return $retstatus
}

###################################
#
# resolvePath - find an executable in a path and return absolute pathname
#
# usage: resolvePath executable [ dir1 ] [ dir2 ] ...
#
###################################
resolvePath() {
	file=$1
	shift
	for dir; do
		fpath=$dir/$file
		if [ -x $fpath -a ! -d $fpath ]; then
			echo $fpath
			return
		fi
	done
}

#########################################
# LOCAL VARIABLES
# They must defined here to resolve the some of parameter resolution
# problem
#########################################
local_variables() {
	GDM_DIR=`/etc/opt/SUNWut/basedir/lib/utgdmconfigpath 2>/dev/null`

	# Set up gconf info
	GCONFTOOL="/usr/bin/gconftool-2"

	if [ -n "$GDM_DIR" ]; then
		OS=`uname -s`
		SUNRAY_ETCDIR="/etc/opt/SUNWut"
		SUNRAY_LIBDIR="/opt/SUNWut/lib"
		KIOSK_ETCDIR="/etc/opt/SUNWkio"
		KIOSK_LIBDIR="/opt/SUNWkio/lib"
		KIOSK_SHAREDIR="/opt/SUNWkio/share"
		SYSTEM_XINITRCD="/etc/X11/xinit/xinitrc.d"
		SUNRAY_XINITRCD="$SUNRAY_ETCDIR/xinitrc.d"
		SUNWUTBegin="# SUNWut BEGIN - do not edit"
		SUNWUTEnd="# SUNWut END"

		# determine whether xinitrc.d scripts are sourced or exec'd
		if isPlatformExecing; then
			XINIT_SOURCES=false
			BASEXSESSION=$SUNRAY_ETCDIR/gdm/Xsession.source_wrapper
		else
			XINIT_SOURCES=true
			BASEXSESSION=
		fi
		
		SUNRAY_GDM_DIR=${SUNRAY_ETCDIR}/gdm
		SUNRAY_GDM_LIBDIR=${SUNRAY_LIBDIR}/gdm
		KIOSK_GDM_DIR=${KIOSK_LIBDIR}/gdm

		SYSTEM_CUSTOMCONF="${GDM_DIR}custom.conf"
		SRCRASHSCRIPT="${SUNRAY_GDM_DIR}/XKeepsCrashing.sunray"
		GDM_PACKAGE_NAME="gdm"
		TMPFILE="/var/opt/SUNWut/tmp/custom.conf.tmp.$$"
		GDMGREETER=$(resolvePath gdmgreeter /usr/lib /usr/libexec)
		KIOSKGREETER_BIN=${KIOSK_GDM_DIR}/kioskgreeter
		SUNRAY_AUTOLOGIN_BIN=${SUNRAY_GDM_LIBDIR}/utgdmautologinuser
		if [ -x "$KIOSKGREETER_BIN" ] ; then
			KIOSKGREETER="${KIOSKGREETER_BIN} " # include separating space
		else
			KIOSKGREETER="" # this is used as prefix to GDMGREETER
		fi
		if [ $OS = "SunOS" ]; then
			AWK=nawk
		else
			AWK=gawk
		fi
		CK_display_file_src=/etc/opt/SUNWut/basedir/lib/gdm/utSunRay.display
		CK_display_file_target=/etc/ConsoleKit/displays.d/utSunRay.display
		CK_Seat_Tool="/usr/sbin/ck-seat-tool"

		# Only use autologin with new gdm
		# Note: isOldGDMEnabled only works after CK_Seat_Tool is set
		if isOldGDMEnabled ; then
			SUNRAY_AUTOLOGIN=
		else
			SUNRAY_AUTOLOGIN="$SUNRAY_AUTOLOGIN_BIN"
		fi
	fi
}

########################################################################
#
# Configurable parameter
#
########################################################################
# NONE

#########################################
#
# variables used in the shared script utctl-shlib
#
#########################################
DESCR="sets up gdm configuration"

########################################################################
#
# Execution starts here
#

PROGPATH=`dirname $0`
. $PROGPATH/utctl-shlib
