#!/bin/ksh -p

# Copyright (c) 02/23/00 Sun Microsystems, Inc. All Rights Reserved
#pragma ident "@(#)utdetach.sh	1.4 01/04/19 SMI"
#
# Default values
#
CONTROL_IPA=0.0.0.0
CONTROL_PORT=7010
# fd number 8 is used for IO to utauthd
SID=""

#
# Subroutines
#

function usage {
	print -u2 "Usage: ${0##*/}"
	exit 1
}


# Open utauthd control port for reading and writing
# Args are IPA, PORT, and FD
function openControl {
	exec 8<> /dev/tcp/$1/$2
}


# Get the session ID of the current session
function getSid {
	/usr/openwin/bin/xprop -root _SUN_SUNRAY_SESSION 2> /dev/null \
		| sed -e 's/.*"\(.*\)"/\1/'
}

#
# Main program
#

#
# No command line arguments needed
#

if [ $# -eq  1 ]
then
    SID=$1
else
    SID=$(getSid)
fi

if [ -z $SID ] 
then
	echo "Session ID cannot be determined."
	usage
fi

openControl $CONTROL_IPA $CONTROL_PORT

print -u8 "control $SID
request disconnect
end
"

cat < /dev/fd/8 | while read line
do
	case $line in
	(ok*|end*)
		print -u8 quit 2>/dev/null
		exit 0;
		;;
	(error*)
		print -u2 -- $line
		exit 1;
		;;
	(quit*)
		exit 0;
		;;
	*)
		;;
	esac
done

exit 0
