#!/bin/ksh -p
#
# ident "@(#)utgdmdynamic.ksh	1.1	12/05/17 Oracle"
#
# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
#

PATH=/usr/bin:/bin:/usr/sbin:/sbin

Seat_Tool="/usr/sbin/ck-seat-tool"
List_Tool="/usr/bin/ck-list-sessions"
Hist_Tool="/usr/bin/ck-history"

Display_Type=utSunRay

if [ ! -x $Seat_Tool ]; then
	if [ -x /usr/bin/gdmdynamic ]; then
		# Old version of GDM (2.20-), just use that wrapper
		exec /usr/bin/gdmdynamic $@
	fi
	print -u2 "$0: System error - can't find appropriate gdmdynamic interface"
	exit 2
fi

usage () {
	echo "$0 [options]"
	echo "   -h, --help     Display this help"
	echo "   -a display     Add a new Sun Ray display"
	echo "   -d display     Delete a Sun Ray display"
	echo "   -r display     No-op subcommand (compatibility with GDM 2.20-)"
	echo "   -b		No-op option (compatibility with GDM 2.20-)"
	echo "   -l             List all Sun Ray displays"
	exit 1
}

optype=""
oparg=""

while getopts ha:d:lr:b opt; do
	case $opt in
		h) usage; exit 1;;
		a) optype="add"; Display="$OPTARG";;
		d) optype="delete"; Display="$OPTARG";;
		l) optype="list";;
		r) optype="no-op";;
		b) ;;
		*) usage; exit 1;;
	esac
done

let OPTIND=$OPTIND-1
if [ $OPTIND != $# ]; then
	print -u2 "$0: Extraneous arguments"
	usage
	exit 1
fi

typeset -i Ret

case $optype in
	add)
# gdmdynamic -a 10=/usr/X11/bin/Xorg
		Display=${Display%=*}
		seatid="${Display_Type}Seat$Display"
		$Seat_Tool -a --display-type=${Display_Type} --seat-id=$seatid display=:$Display
		Ret=$?
		if (( $Ret != 0 )); then
			print -u2 "$0: $Seat_Tool -a exited with bad status $Ret"
			exit $Ret
		fi
		;;
	delete)
# gdmdynamic -d 10
# Note that \x27 represents a single-quote to gawk. We need to strip quotes.
		ssid=$($List_Tool -f session-id,x11-display,display-type \
			| gawk -v disp="':$Display'" -v type="'${Display_Type}'" '
$2 == disp && $3 == type { gsub ( "\x27", "", $1 ); print $1 }
')
		if [ -n "$ssid" ]; then
			$Seat_Tool -d --session-id=$ssid
			Ret=$?
			if (( $Ret != 0 )); then
				print -u2 "$0: $Seat_Tool -d exited with bad status $Ret"
				exit $Ret
			fi
		fi
		;;
	list)
# gdmdynamic -l
# Note that \x27 represents a single-quote to gawk. We need to strip quotes.
		sessions=$($List_Tool -f session-id,x11-display,display-type \
			| gawk -v type="'${Display_Type}'" '
$3 == type { gsub ( "\x27", "", $2 ); print $2 }
')
		dpys=""
		for i in $sessions
		do
			if [ -n "$i" ]; then
				dpys="$i,,;$dpys"
			fi
		done
		echo $dpys
		;;
	no-op) ;;
	* )
		print -u2 "$0: System error - unrecognized operation '$optype' ($0 $@)"
		usage
		exit 2
		;;
esac
exit 0
