#!/usr/bin/sh
#
# Copyright (c) 1997-2001 by Sun Microsystems, Inc.
# All rights reserved.
#

#ident "@(#)pnm 1.18 01/03/14 SMI"

#
# /etc/init.d/pnm - Start/Stop pnmd 
#

PATH=/usr/bin:/bin
PNMD_TAG=pnmd
PMFADM=/usr/cluster/bin/pmfadm
SERVER=pnmd

getpid()
{
	pid=`/usr/bin/ps -e | /usr/bin/grep pnmd | \
		/usr/bin/sed -e 's/^  *//' -e 's/ .*//'`
	echo "$pid"
}

#
# main()
#

#
# Only run this script in cluster mode. There's no support for
# running PNM in non-cluster mode.
#
/usr/sbin/clinfo >/dev/null 2>&1 || exit 0

#
# Is pmf available?
#
test -x $PMFADM && pmf_avail=yes

case $1 in 
'start')

	pid=`getpid`
	if test ! "$pid" ; then
		test "$pmf_avail" &&
			#
			# Start pnmd under pmf. Restart pnmd always if it
			# dies (-n -1), and monitor only pnmd but not its
			# forked commands (-C 1). Note that we couldn't
			# do -C 0, since pnmd forks itself as part of
			# its daemonization.
			#
			$PMFADM -c $PNMD_TAG -n -1 -C 1 /usr/cluster/bin/pnmd
		if [ $? != 0 ]; then
			/usr/bin/logger -p local0.err -t INITPNM "Error: Can't run pmfadm. Exiting without starting ${SERVER}."
			exit 1
		fi

		#
		# Do probe_&_wait till rpc svc has been set up.
		# We don't wait if there're only config errors.
		# A return code 5 from pnmstat indicated pnmd
		# has not yet started. We'll give it some time.
		#

		/usr/bin/sleep 1
		retries=10
		/usr/cluster/bin/pnmstat 2>/dev/null 1>/dev/null
		while [ $? -eq 5 ]
		do
			# Give up after a couple of retries
			if [ $retries -eq 0 ]; then
				/usr/bin/logger -p local0.err -t INITPNM "Can't register PNM RPC services."
				exit 1
			fi

        		/usr/bin/sleep 3
			retries=`/usr/bin/expr $retries - 1`
			/usr/cluster/bin/pnmstat 2>/dev/null 1>/dev/null
		done
	fi
	;;

'stop')

	pid=`getpid`
	if test "$pid"
	then
		if [ "$pmf_avail" != "" ]; then
			$PMFADM -l $PNMD_TAG >/dev/null 2>&1
			if [ $? = 0 ]; then
				$PMFADM -s $PNMD_TAG TERM && killed=yes
			fi
		fi
		if [ "$killed" = "" ]; then
			kill -TERM $pid
		fi
	fi
	;;
*)
	echo "usage: /etc/init.d/pnm {start|stop}"
	;;
esac


