#!/bin/ksh -p
#
# Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
#
# ident "@(#)ut_audio_speculative_allocate.ksh 1.5     07/06/08 SMI"
#
#
# This is the speculative device allocate script for the Sun Ray DTU internal audio device.
#
#  calling:
#	ut_audio_speculative_allocate [ -A | -D ] -z zonename -x XID -u username -d devtag
#
#    returns:
#	0 - device allocated
#	1 - device not allocated
#

PATH="/usr/bin:/usr/sbin"

mod="`basename $0`"

# print usage and exit
usage() {


	print -u 2 "usage: $mod [ -A | -D ] -z zonename -x XID -u username -d devtag"
	exit 1

}

# main program

id="/usr/xpg4/bin/id -u"
utaudio_dev_class="sraudio"	# base name of device tag, i.e. sraudio<n>

	ops=""
	zonename=""
	xdpy=""
	username=""
	devtag=""

	while getopts ADz:x:u:d: c 2>/dev/null
	    do
	        case $c in
		    A) ops="allocate" ;;
		    D) ops="deallocate" ;;
		    z) zonename=$OPTARG ;;
		    x) xdpy=$OPTARG ;;
		    u) username=$OPTARG ;;
		    d) devtag=$OPTARG ;;
		   \?) usage ;;
		esac
	      done

	if [[ ! ( -n $zonename && -n $xdpy  && -n $username && -n $devtag && -n $ops ) ]] ; then
		usage
	fi

	# we only support the allocate operation
	if [ "$ops" != "allocate" ] ; then
		print -u 2 "$mod: invalid option"
		usage
	fi

	# get username from username
	uid="`$id $username`"

	# get the list of audio devices that are allocated for this zone/XID/username
	# we don't care what they are or how many there are, just if there are
	# any that are allocated
	devlist="`list_devices -a -u -U $uid -z $zonename | fgrep $utaudio_dev_class | fgrep xdpy=$xdpy`"

	if [ "$devlist" != "" ] ; then

	    max_alloc_cnt=10	# maximum number of allocate attempts
	    alloc_delay=1	# delay time (secs) between allocate attempts
	    alloc_cnt=0		# count of allocate attempts
	    alloc_success=0	# allocate sucessful
	    alloc_nodev=20	# allocate can't find device in database

	    alloc_status=$alloc_nodev
	    while [ $alloc_cnt -lt $max_alloc_cnt ]
	      do
		allocate -s -F -U $username -z $zonename $devtag
		alloc_status=$?
		case $alloc_status in
		    $alloc_success) echo "allocated $devtag" ;
		    		    exit 0 ;;
		      $alloc_nodev) echo "waiting($alloc_cnt) for database update for $devtag" ;;
		    		 *) echo "not allocating $devtag, allocate failure: $alloc_status" ;
				    exit 1 ;;
		esac
		alloc_cnt="`expr $alloc_cnt + 1`"
		sleep $alloc_delay
	      done

	    echo "not allocating $devtag, too many failed allocate attempts"
	else
	    echo "not allocating $devtag, no devlist found"
	fi

	exit 1

