#!/bin/sh
#
# Copyright (C) 2003 Red Hat, Inc.
#
# This program is Free Software.  You may modify and/or redistribute it under
# the terms of the GNU General Public License version 2, or (at your option)
# any later version.
#
# description:  Starts and stops Red Hat Service (resource group) Manager
# chkconfig: 2345 99 01
#

# Source function library
. /etc/init.d/functions

# Grab the network config file
. /etc/sysconfig/network

# Grab cluster start config if it exists
[ -f /etc/sysconfig/cluster ] && . /etc/sysconfig/cluster

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

export PATH

ID="Cluster Service Manager"
RGMGRD="clurgmgrd"
CFG_FILE="@CONFDIR@/@CONFFILE@"

LOG_ERR=3
LOG_WARNING=4
LOG_NOTICE=5
LOG_INFO=6


#
# log_and_print <level> <message>
#
log_and_print()
{
	if [ -z "$1" -o -z "$2" ]; then
		return 1;
	fi

	clulog -p $$ -n "rgmanager" -s $1 "$2"
	echo $2

	return 0;
}


#
# Bring down the cluster on a node.
#
stop_cluster()
{
	kill -TERM `pidof $RGMGRD`

	while [ 0 ]; do

		if [ -n "`pidof $RGMGRD`" ]; then
			echo -n $"Waiting for services to stop: " 
			while [ -n "`pidof $RGMGRD`" ]; do
				sleep 1
			done
			echo_success
			echo
		else
			echo $"Services are stopped."
		fi

		# Ensure all NFS rmtab daemons are dead.
		killall $RMTABD &> /dev/null
		
		rm -f /var/run/$RGMGRD.pid

		return 0
	done
}


case $1 in
	start)
		#
		# If we're not configured, then don't start anything.
		#
		if [ "${NETWORKING}" != "yes" ]; then
			echo "Cannot start $ID: Networking not configured"
			exit 1
		fi
		[ -f "$CFG_FILE" ] || exit 0

		echo -n $"Starting $ID: "
		daemon $RGMGRD $RGMGR_OPTS
		ret=$?
		echo

		# To be consistent...
		if [ $ret -eq 0 ]; then
			touch /var/lock/subsys/rgmanager
		fi
		exit $ret
		;;

	restart)
		$0 status &> /dev/null
		if [ $? -ne 1 ]; then
			$0 stop
		fi
		$0 start
		;;
		
	condrestart)
		$0 status $> /dev/null
		if [ $? -eq 0 ]; then
			$0 stop
			$0 start
		fi
		;;

	reload)
		clulog -p $LOG_NOTICE "Reloading Resource Configuration."
		echo -n $"Reloading Resource Configuration: "
		killproc $RGMGRD -HUP
		rv=$?
		echo

		exit $rv
		;;

	status)
		status $RGMGRD
		exit $?
		;;

	stop)
		if [ -n "`pidof $RGMGRD`" ]; then
			log_and_print $LOG_NOTICE "Shutting down $ID..."
			stop_cluster
		fi

		rm -f /var/lock/subsys/rgmanager
		log_and_print $LOG_NOTICE "$ID is stopped."
		;;
	*)
		echo "usage: $0 {start|restart|condrestart|reload|status|stop}"
		exit 1
		;;
esac

exit 0
