#!/bin/ksh -p
#
# ident "uttsc.ksh $Date: 2006-04-28 16:18:59 -0700 (Fri, 28 Apr 2006) $ $Revision: 2200 $ SMI"
#
# Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

PATH=/bin:/usr/bin
SUNWUTETC=/etc/opt/SUNWut
SRSS_PKG_LOC="`$SUNWUTETC/basedir/lib/utprodinfo -r SUNWuto`/SUNWut"
SRSS_BIN=$SRSS_PKG_LOC/bin
UTADMIN_CONF=$SUNWUTETC/utadmin.conf
SRSS_DYNAMIC_ADMIN=$SRSS_PKG_LOC/lib/libutadmin.so.1

SRCBINARY=/opt/SUNWuttsc/lib/uttsc-bin

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
}

# 1. Check for SRSS version.. as only 3.1 and above are supported

majorVersion=`$SUNWUTETC/basedir/lib/utprodinfo -p SUNWuto PRODVERS | awk -F. '{print $1}'`
minorVersion=`$SUNWUTETC/basedir/lib/utprodinfo -p SUNWuto PRODVERS | awk -F. '{print $2}'`

if [[ $majorVersion -lt 3 || $majorVersion -eq 3 && $minorVersion -lt 1 ]]; then
	print "Only SRSS 3.1 and above are supported"
	exit 1
fi

# 2. Check for latest patch, by looking for the dynamic library.
if [[ ! -f $SRSS_DYNAMIC_ADMIN ]]; then
        print "Unable to launch Sun Ray Connector. Please ensure that the latest SRSS patch is installed."
        exit 1
fi

# 3. Check if configured mode for SRSS
if [[ ! -f $UTADMIN_CONF ]]
then
        print "Please configure SRSS before using Sun Ray Connector for Windows Operating Systems."
	exit 1
fi

# 4. Execute the audio launcher

# need to keep default if utaudio fails.

OLD_AUDIODEV=$AUDIODEV

AUDIODEV="$($SRSS_BIN/utaudio utaudioid-$$ &)"

if [[ -z $AUDIODEV ]]; then
	# Check if it's Trusted Solaris Environment by checking
	# the existence of trusted network remote-host database
        if [[ -f /etc/security/tsol/tnrhdb ]]; then
		if [[ -n $OLD_AUDIODEV ]]; then
			device_owner=`ls -l $OLD_AUDIODEV | awk '{print $3}'`
			userid=$USER
			# if device owner is the same as logged in user, then
			# device has been allocated on Trusted Solaris Environment
			# and can be used by application.
			if [[ $device_owner = $userid ]]; then
				AUDIODEV=$OLD_AUDIODEV
			fi
		fi
        else
                print "Unable to launch utaudio. Using default audio device."
                AUDIODEV=$OLD_AUDIODEV
        fi
fi

export AUDIODEV

trap "cleanup 1" HUP INT TERM KILL QUIT 

export UTAUDIODEV=$AUDIODEV

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

$SRCBINARY "$@" 
return_status=$?

cleanup $return_status

