#!/bin/ksh -p

#
# ident "@(#)utdetach.sh	1.12 08/02/27 SMI"
#
# Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

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

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

#
# Solaris 10 Trusted Extension guard
#
ORIGIN=`/usr/bin/dirname $0`
UTIL_LIB=${ORIGIN:-/opt/SUNWut/lib}/../lib/support_lib/util_lib
. $UTIL_LIB
FailExecInLocalZoneOnTx 
#
# Solaris 10 Trusted Extension guard 
#

#
# 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
}

# Get a host IP address
function getHostIPA {
	IP=`getent hosts $1 2>/dev/null | awk '{print $1 ; exit}' `
	if [ -z "$IP" ]
	then
		IP=`print $1 | sed -n '/^[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$/p'`
	fi
	print $IP
}

#
# Main program
#

#
# Process command line arguments, if any
#
while  getopts $OPTSTR OPT 2>/dev/null
do
    case "$OPT" in
	h) usage 0;;
	s) # Read SID from stdin 
	   read SID;;
       \?) print -u2 "Invalid option."
	   usage 1;;
    esac
done

# Confirm arguments 
if [[ `expr $OPTIND - 1` != $# ]]
then
        usage 1
fi

#
# If SID is not specified, get the SID of current session.
#
if [ -z $SID ]
then
    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

SIDHOST=`echo $SID | sed -n 's/^\([^:]*\):.*/\1/p'`

CONTROL_IPA=$(getHostIPA $SIDHOST)
if [ -z $CONTROL_IPA ]
then
	print -u2 "Error: cannot resolve hostname $SIDHOST"
	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
