#!/bin/ksh -pu

# Copyright (c) 05/11/99 Sun Microsystems, Inc. All Rights Reserved
# @(#)utidle.sh	1.3 99/05/11

# Examples:
#	/opt/SUNWut/lib/utidle /var/opt/SUNWUt/displays/9 true
#	/opt/SUNWut/lib/utidle /var/opt/SUNWUt/displays/121 false

ME=$0

# Parse arguments

eval $(sed -n 's/SESSION=\([^:]*\):\([^:\]*\):\(.*\)$/host=\1\
port=\2\
sid=\3/p' $1)

idle=$2

if [ -z "$host" -o -z "$port" -o -z "$sid" -o -z "$idle" ]
then
	exit 1;
fi

function openControl {
	exec 8<> /dev/tcp/$1/$2
}

# translate a host name to its IP address
function getHostIPA {
	host=$1
	if [ "$host" = "$(</etc/nodename)" ]
	then
		print 0.0.0.0
		return
	fi
	case $host in
	localhost | 127.0.0.1 | 0.0.0.0)
		print 0.0.0.0
		return;;
	esac

	hostipa=$(getent hosts $host 2>/dev/null | cut -f1 -d'	')
	print $hostipa
}

ipa=$(getHostIPA $host)
openControl $ipa 7010

print -u8 "control $host:$port:$sid
request annotate
idle=$idle
end
quit
"

cat < /dev/fd/8 | while read line
do
	case $line in
	ok|end)
		print -u8 quit
		exit 0;
		;;
	quit)
		exit 0;
		;;
	*)
		;;
	esac
done

exit 0
