#!/sbin/sh
#
#ident	"@(#)init.wbem.sh	1.66	03/04/22 SMI"
#
# Copyright 2000-2003 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#

if [ -x /usr/sadm/lib/smc/bin/smcboot ]; then
	VIPER_HOME=/usr/sadm/lib/smc
	export VIPER_HOME

	SMC_PORT=`getent services smc | awk '{print $2}' | cut -d'/' -f1`
	if [ "$SMC_PORT" = "" ]; then
	    SMC_PORT=898
	fi

fi

stopCimom () {
    for daemon in cimbootserver cimomserver ; do
	    pidfile=/var/sadm/wbem/logr/$daemon.pid
	    if [ -f $pidfile ]; then
		    pid=`/usr/bin/cat $pidfile`
		    [ "$pid" -gt 0 ] && kill $pid >/dev/null 2>&1
		    rm -f $pidfile
	    fi
    done
}

case "$1" in
'start')
	if [ -n "$VIPER_HOME" ]; then
		# We try to be intelligent about when this script is run.
		# If started during system boot (as evidenced by /etc/rc
		# included in the path AND the script isn't referred to
		# to as "init.wbem"), then we start using smcboot, which
		# will delay SMC server startup until the 1st connection
		# from the SMC console.
		#
		# Otherwise, it is safe to assume that system boot is 
		# completed, and we can force the server to start immediately.
		#
		rcDir=`/usr/bin/dirname $0 | grep "/etc/rc"`
		file=`basename $0`
		if [ "${file}" = "init.wbem" -a "${rcDir}" = "" ]; then

			# If smcboot is running, stop it first, otherwise
			# you get collision on the same port.
			smcboot=`/bin/pgrep smcboot`
			if [ -n "$smcboot" ]; then
				$0 stop
			fi

			# Start server
			$VIPER_HOME/bin/smcwbemserver -p $SMC_PORT start >/dev/msglog 2>&1 &
		else
			$VIPER_HOME/bin/smcboot >/dev/msglog 2>&1 &
		fi
	else
		# Stop and start the CIMOM.
		stopCimom
		umask 066; /usr/sadm/lib/wbem/cimomboot "$@" >/dev/msglog 2>&1 &
		echo $! >/var/sadm/wbem/logr/cimbootserver.pid
	fi
	;;

'stop')
	if [ -n "$VIPER_HOME" ]; then
		if [ -f /var/run/smc$SMC_PORT/boot.pid ]; then
			kill -TERM `cat /var/run/smc$SMC_PORT/boot.pid`

			# Need to give the killed process enough time
			# to catch the TERM signal and clean up
			sleep 1
		else
			$VIPER_HOME/bin/smcserver -p $SMC_PORT stop
		fi

		# Directory containing socket information could still be 
		# around if server died unexpectedly or user killed it manually.
		# So it's important to delete it, otherwise there will be 
		# problems on the next start.  The SMC server scripts should
		# take care of this, so it's unlikely the directory will exist
		# at this time.  But just in case...
		#
		if [ -d /var/run/smc${SMC_PORT} ]; then
			rm -rf /var/run/smc${SMC_PORT}
			echo "Server found to be unstable."
			echo "It has been repaired and can now be restarted."
		fi
	else
		stopCimom
	fi
	;;

status)
	if [ -n "$VIPER_HOME" ]; then
		$VIPER_HOME/bin/smcserver -p $SMC_PORT status
	fi
	;;

*)
	echo "Usage: $0 { start | stop | status }"
	exit 1
	;;
esac
exit 0
