#!/bin/sh
#
#pragma ident	"@(#)initfed	1.11	01/03/14 SMI"
#
# Copyright (c) 1998-2001 by Sun Microsystems, Inc.
# All rights reserved.
#

# Start/stop processes required for init fed

LIBSCDIR=/usr/cluster/lib/sc
BINDIR=/usr/cluster/bin
USRBIN=/usr/bin
SERVER=rpc.fed
PROGNUM=100142
VERSNUM=1
svcfound=no

case "$1" in
'start')
	# test whether we are a cluster and exit if not a cluster
	/usr/sbin/clinfo > /dev/null 2>&1
	if [ $? != 0 ] ; then
		exit 0
	fi

	# Find if an instance of rpc.fed is already running and if yes exit
	# We only allow one rpc.fed at a time.
	pidlist=`${USRBIN}/ps -e | ${USRBIN}/grep ${SERVER} \
		| ${USRBIN}/awk '{print $1}'`
	if [ -n "${pidlist}" ] ; then
		${USRBIN}/logger -p local0.err -t INITFED "Error: ${SERVER} is already running."
                exit 1;
	fi

        # check that rpc.pmfd is up by doing a stat command
	# no need to loop since we looped when we started rpc.pmfd
	${BINDIR}/pmfadm -L 2>/dev/null 1>/dev/null
        if [ $? -ne 0 ]; then
       		${USRBIN}/logger -p local0.err -t INITFED "Error: rpc.pmfd is not running."
		exit 1
	fi

	# start the server
	${LIBSCDIR}/${SERVER}
	if [ $? -ne 0 ]; then
		${USRBIN}/logger -p local0.err -t INITFED "Error: Can't start ${SERVER}."
		exit 1
	fi

	# sleep for 2 sec to give the server the chance to come up
	${USRBIN}/sleep 2

	# loop for 2 min checking that the server is up
        # by doing a rpcinfo command on the loopback interface
	for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24; do
        	if ${USRBIN}/rpcinfo -l 127.0.0.1 ${PROGNUM} ${VERSNUM} 2>/dev/null | \
	            ${USRBIN}/grep ${PROGNUM} >/dev/null 2>&1; then

			svcfound=yes
			break
		fi
		${USRBIN}/sleep 5
	done

	if [ $svcfound = no ]; then
       		${USRBIN}/logger -p local0.err -t INITFED "Error: Timed out waiting for ${SERVER} service to register."
		exit 1
	fi

	;;

'stop')
	# Find if rpc.fed is running and if yes kill it.
	# This works on a list, but there shouldn't be more than one
	# instance running (see start case).
	pidlist=`${USRBIN}/ps -e | ${USRBIN}/grep ${SERVER} \
		| ${USRBIN}/awk '{print $1}'`
	if [ -n "${pidlist}" ] ; then
	        # kill each process in list
	        for pid in ${pidlist}
	        do
	                kill -TERM ${pid}
                        echo "Notice: ${SERVER} is being stopped."
	        done
	fi

	;;
*)
	echo "Usage: /etc/init.d/initfed { start | stop }"
	;;
esac
