#!/bin/ksh -p
#
# ident "@(#)utauthd.sh	1.26 02/09/05 SMI"
#
# Copyright 1998-2002 Sun Microsystems, Inc.  All rights reserved.
#

function usage {
	print -u2 "$prog: unknown option $OPTARG"
	print -u2 "Usage: $prog [-b|-e] [-s signal] [-n fds]"
	print -u2 "    -e # End execution of authentication manager"
	print -u2 "    -s # Signal to send to utauthd"
	print -u2 "    -b # Begin execution of authentication manager (default)"
	print -u2 "    -n # Number of file descriptors to make available"
	exit 1
}

SUNWUTLIB=$(pkginfo -r SUNWuto 2>/dev/null)/SUNWut/lib

JAVA_HOME=$(pkginfo -r SUNWutj 2>/dev/null)/SUNWut/jre
JAVA=$JAVA_HOME/bin/java

PATH=/usr/bin:/usr/sbin:/bin
CLASSPATH=$JAVA_HOME/lib/:$JAVA_HOME/jre/lib/rt.jar
CLASSPATH=$SUNWUTLIB/utauthd.jar:$CLASSPATH
CLASSPATH=$SUNWUTLIB/sdk.jar:$CLASSPATH
CLASSPATH=$SUNWUTLIB/protocol.jar:$CLASSPATH
CLASSPATH=$(print $SUNWUTLIB/modules/AuthModule*.jar | tr ' ' ':'):$CLASSPATH
if [ -f "$SUNWUTLIB/admin.jar" ]
then
	CLASSPATH=$SUNWUTLIB/admin.jar:$CLASSPATH
fi
export CLASSPATH

export LD_LIBRARY_PATH=/opt/SUNWut/lib

action=""
signal=TERM
#maxfds=$(ulimit -n)
maxfds=9000

prog=${0##*/}
while getopts bdens c
do
	case $c in
	b)	# Begin
		[[ -n "$action" ]] && usage || action="start"
		;;
	e)	# End
		[[ -n "$action" ]] && usage || action="stop"
		;;
	s)	# Signal
		signal=$OPTARG
		;;
	n)	# Max number of file descriptors
		maxfds=$OPTARG
		;;
	\?)
		usage;
		;;
	esac
done

[[ -z "$action" ]] && action=start

if [[ $action == start ]]
then
	ulimit -n $maxfds	# Default number of file descriptors is usually 64

	# Set up the JRE size parameters - use 1% of main memory
	memuse=`/usr/sbin/prtconf |
		awk '/Memory size:/ { printf "%d\n", $3 / 100 }'`
	if [ $memuse -lt 16 ]; then
		memuse=16
	fi

	CURR_POLICY=$(/opt/SUNWut/sbin/utpolicy | nawk '/^#/ {next} {print}')

	if [[ $? -eq 0 ]]
	then
		/opt/SUNWut/lib/utgenpolicy $CURR_POLICY
	fi

	exec /bin/env -i	\
		PATH="$PATH"	\
		CLASSPATH="$CLASSPATH:$LD_LIBRARY_PATH"	\
		LD_LIBRARY_PATH="$LD_LIBRARY_PATH"	\
		JAVA_HOME=$JAVA_HOME			\
		$JAVA -native auth.utauthd.utauthd 
else
	/usr/bin/ps -eo pid,args |
	    /usr/bin/grep "auth.utauthd.utauthd" |
	    /usr/bin/fgrep -v grep |
	    while read pid args
	do
		kill -$signal $pid
	done
fi
