#!/bin/ksh -p

#
# ident "@(#)utdetach.sh	1.7 04/08/07 SMI"
#
# Copyright 2000-2001,2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

UTBASE=/etc/opt/SUNWut/basedir
UTLIB=$UTBASE/lib
UTNETPIPE="$UTLIB/utnetpipe"
UTXPROP="$UTLIB/utxprop"
PROG=${0##*/}
OPTSTR="h"

#
# Default values
#
CONTROL_IPA=0.0.0.0
CONTROL_PORT=7010

SID=""

#
# Subroutines
#

function usage {
	typeset OUT=""
	if [[ $1 -ne 0 ]]; then
		OUT="-u2"
	fi
	print ${OUT} "Usage: $PROG"
	print ${OUT} " -h	# print this message"
	exit $1
}

# Get the session ID of the current session
function getSid {
	$UTXPROP -s 2> /dev/null
}

#
# Main program
#

#
# No command line arguments needed
#
while  getopts $OPTSTR OPT 2>/dev/null
do
    case "$OPT" in
	h) usage 0;;
       \?) print -u2 "Invalid option."
	   usage 1;;
    esac
done


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

if [ -z $SID ] 
then
	echo "Sun Ray Session ID cannot be determined. $PROG is only supported in a Sun Ray session."
	exit 1
fi

print "control $SID
request disconnect
end" | $UTNETPIPE "$CONTROL_IPA" "$CONTROL_PORT" | while read line
do
	case $line in
	(ok*|end*)
		exit 0;
		;;
	(error*)
		print -u2 -- $line
		exit 1;
		;;
	(quit*)
		exit 0;
		;;
	*)
		;;
	esac
done

exit 0
