#!/bin/ksh -p
# @(#)waitforprimary.start.sh	1.1 00/05/31
set -u

# The following magic comment inhibits starting an X server
## utdtsession no-xinit

UTVAR=/var/opt/SUNWut
UTOPT=$(/usr/bin/pkginfo -r SUNWuto)/SUNWut
UTLIB=${UTOPT}/lib
UTBIN=${UTOPT}/bin
UTSBIN=${UTOPT}/sbin
PATH=${UTSBIN}:${UTBIN}:${UTLIB}:/usr/bin:/usr/sbin

cd /tmp
function cleanup {
	${UTLIB}/utdtsession -t $fulltoken delete <<-!
	!
}

trap "cleanup" 0 1 2

if [ $# != 2 ]
then
	exit 1
fi

fulltoken=${1}

TokenFile=$(print $UTVAR/tokens/$fulltoken | sed -e 's=\.=/=g')
SID=$(cat $TokenFile)

iter=0
while [ 1 -eq 1 ]
do
	exec 8<> /dev/tcp/0.0.0.0/7010
	print -u8 "findPrimary $SID
end
"
	where=$(cat </dev/fd/8)

	if [ ! -z "$where" ]
	then
		#
		# Got somewhere to go
		#
		break;
	fi

	#
	# Check every 5 seconds for a minute, then every 15 seconds
	#
	if [ $iter -lt 16 ]
	then 
		#
		# Display the icon for 1 minute 5x1 + 11x5
		#
		if [ $iter -lt 5 ]
		then
			#
			# 4 x 0.25 = 1sec
			#
			cnt=4
		else
			#
			# 20 x 0.25 = 5sec
			#
			cnt=20
		fi

		print $SID | \
		    ${UTLIB}/yuvfile -i - -x 576 -y 448 -d 250 -n $cnt \
			${UTLIB}/waiting.yuv
	else
		sleep 15
	fi

	((iter+=1))
done

#
# Finally located the primary (or an error). Get out of here
#
# BUT first, we need to delete our session before we do so to make sure if we
# come right back, we'll see no current session for the token and will start
# something new. We're on our way out so this is OK.
#
# If the secondary is somewhere else, we could redirect there. However
# redirect won't do anything if "there" is "here"; i.e. a redirect to self is
# a no-op and we won't reauthenticate. Instead, we send a disconnect to the
# unit after removing our session. When it reauthenticates it will find the
# right place and automatically get directed there.
#

# Remove the trap handler
trap "" 0 1 2

# Do it ourselves
cleanup

#
# Now send the command and wait for result
#
exec 8<> /dev/tcp/0.0.0.0/7010
print -u8 "control $SID
request disconnect
tokenRestart=true
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
