#!/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

# Grap 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="/etc/cluster/cluster.conf"

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

#
# Only root wants to run this...
#
[ `id -u` = 0 ] || exit 0

#
# If we're not configured, then don't start anything.
#
[ "${NETWORKING}" = "yes" ] || exit 0
[ -f "$CFG_FILE" ] || exit 0


#
# 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)
		echo -n $"Starting $ID: "
		daemon $RGMGRD $RGMGR_OPTS
		echo

		# To be consistent...
		touch /var/lock/subsys/rgmanager
		;;

	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."
		;;
esac
