#!/bin/bash
#
# BOOTH daemon init script for LSB-compliant Linux distributions.
#
# booth-arbitrator	BOOTH arbitrator daemon
#
# chkconfig: - 20 20
# processname:  boothd
# pidfile:      /var/run/booth.pid
# description:  Cluster Ticket Registry
### BEGIN INIT INFO
# Provides: booth
# Required-Start: $network $syslog
# Required-Stop: $network $syslog
# Should-Start:
# Should-Stop:
# Default-Start: 3 5
# Default-Stop: 0 6
# Short-Description: start and stop BOOTH arbitrator daemon
### END INIT INFO

prog="boothd"
exec="/usr/sbin/$prog"
type="arbitrator"       
lockfile="/var/run/booth.pid"

BOOTH_DAEMON_STARTED=0
BOOTH_DAEMON_STARTING=1
BOOTH_DAEMON_EXIST=2
BOOTH_DAEMON_NOT_RUNNING=3
BOOTH_ERROR_GENERIC=4

. /etc/rc.status

internal_status() {
	checkproc $exec > /dev/null 2>&1
	return $?
}

check_status() {
	internal_status ; rc=$?

	if [ $rc == 0 ];then
		pidnum=$(cat $lockfile|awk '{print $1}')
		daemonstate=$(cat $lockfile |awk '{print $2}')
		if cat /proc/$pidnum/cmdline |grep $type > /dev/null 2>&1 ; then
			case $daemonstate in
			$BOOTH_DAEMON_STARTED) return $BOOTH_DAEMON_STARTED;;
			$BOOTH_DAEMON_STARTING) return $BOOTH_DAEMON_STARTING;; #arbitrator daemon is Running
			*) return $BOOTH_ERROR_GENERIC;;
			esac
		else
			return $BOOTH_DAEMON_EXIST  #site daemon is Running
		fi
	else
		return $BOOTH_DAEMON_NOT_RUNNING #BOOTH daemon is not running    
	fi    
}

status() {
	echo -n "BOOTH arbitrator daemon is "
	if check_status; then
		echo "Running"
		return 0
	else
		echo "Stopped"
		return 7
	fi
}

start() {
	[ -x $exec ] || exit 5
	check_status; rc=$?
	case "$rc" in
	$BOOTH_DAEMON_STARTED)
		echo "BOOTH arbitrator daemon is Running"
		return 0
		;;
	$BOOTH_DAEMON_STARTING)
		echo "BOOTH arbitrator daemon is Running"
		return 0
		;;
	$BOOTH_DAEMON_EXIST)
		echo "BOOTH site daemon is Running"
		return 1
		;;
	$BOOTH_DAEMON_NOT_RUNNING)
		echo -n $"Starting BOOTH arbitrator daemon: "		
		startproc $exec $type
		rc_status -v
		;;
	esac
}

stop() {
	check_status; rc=$?
	case $rc in
	$BOOTH_DAEMON_STARTED);;
	$BOOTH_DAEMON_STARTING);;
	$BOOTH_DAEMON_EXIST) 
		echo "BOOTH site daemon is running."
		return $OCF_ERR_GENERIC;;
	$BOOTH_DAEMON_NOT_RUNNING)
		echo "BOOTH arbitrator daemon is not running."
		return $OCF_SUCCESS 
	;;
	*) return $OCF_ERR_GENERIC;;
	esac
	
	echo -n $"Stopping BOOTH arbitrator daemon: "
	killproc -p $lockfile $prog -TERM
	rc_status -v
}

wait_for_stop() {
	while [ -e $lockfile ]; do
		sleep .5
	done
}

restart() {
	stop
	wait_for_stop
	start
}

case "$1" in
	start|stop|restart)
        $1
        ;;
	reload|force-reload)
        restart
        ;;
	condrestart|try-restart)
	[ ! -f "$lockfile" ] || restart
        ;;
  status)
        status $prog
        ;;
  *)
        echo $"Usage: $0 {start|stop|restart|try-restart|condrestart|reload|force-reload|status}"
        exit 2
esac
