#!/bin/ksh -p
#
# ident "uttsc.ksh $Date: 2007-05-30 16:44:55 -0700 (Wed, 30 May 2007) $ $Revision: 143 $ SMI"
#
# Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

PATH=/bin:/usr/bin
SUNWUTETC=/etc/opt/SUNWut
SRSS_PKG_LOC=""
SRSS_BIN=""
IS_SYSTEM_LABELED=1

OS=`/bin/uname -s`

#  If system is labeled (aka Trusted Extensions), sets the IS_SYSTEM_LABELED to 0
#  1 otherwise.
#
function smf_is_system_labeled {
        [ ! -x /bin/plabel ] && return 1
        /bin/plabel > /dev/null 2>&1
        IS_SYSTEM_LABELED=$?
} 

function cleanup {
        AUDIO_PROC=`ps -ef | grep utaudioid-$$ | grep -v grep | awk '{print $2}'`
	if [[ -n $AUDIO_PROC ]]; then
		kill -KILL $AUDIO_PROC
	fi
        exit $1
}

#
#MAIN
# 
# 1.  Check whether this program is run from a Sun Ray session
if [[ -z "${SUN_SUNRAY_TOKEN:-}" ]]
then
	print -u2 "Error: Sun Ray Token ID cannot be determined. Sun Ray Connector can only be launched from a Sun Ray session."
	exit 1
fi

# 2. Is this a trusted system ? 
smf_is_system_labeled

# Not really relocatable on TX, and no utprodinfo available either, hence :

if [[ $IS_SYSTEM_LABELED -eq 0 ]]; then
  SRCBINARY=/opt/SUNWuttsc/lib/uttsc-bin
  SRSS_BIN=/opt/SUNWut/bin
else
  SRC_PKG_LOC="`$SUNWUTETC/basedir/lib/utprodinfo -r SUNWuttsc`/SUNWuttsc"
  SRCBINARY=$SRC_PKG_LOC/lib/uttsc-bin
  SRSS_PKG_LOC="`$SUNWUTETC/basedir/lib/utprodinfo -r SUNWuto`/SUNWut"
  SRSS_BIN=$SRSS_PKG_LOC/bin
fi


# 3. Execute the audio launcher
# need to keep default if utaudio fails.

OLD_AUDIODEV=$AUDIODEV

AUDIODEV="$($SRSS_BIN/utaudio utaudioid-$$ &)"
if [[ -z $AUDIODEV ]]; then
	print "Unable to create new audio device. Using default audio device."
	AUDIODEV=$OLD_AUDIODEV
fi

export AUDIODEV
allocated=0

# check that AUDIODEV is allocated for TX , Loop for 3 seconds to verify that.
# utaudio does not tell us whether audiodev has been allocated or not, hence
# we need to verify this outside to be able to give the user useful information.
if [[ $IS_SYSTEM_LABELED -eq 0 ]]; then
	for i in [ 1 2 3 ] ;
	do
		# AUDIODEV  is readable, that means it is allocated...
		# AUDIODEV can be default device or newly created device, based on prev utaudio 
		# launch.
		if [[ -r $AUDIODEV ]]; then
			allocated=1 
			break
		fi
		sleep 1
	done
	if [[ $allocated == 0 ]] ; then
		print "Device $AUDIODEV is not allocated. Audio will not work in this session. Continuing.."
	fi
fi

trap "cleanup 1" HUP INT TERM KILL QUIT 

export UTAUDIODEV=$AUDIODEV

# 4. Start the uttsc binary. On exit, cleanup and exit with return status from binary.

$SRCBINARY "$@" 
return_status=$?

cleanup $return_status

