#!/bin/bash
#
# qdiskd quorum disk daemon
#
# chkconfig: - 22 78
# description: Starts and stops the quorum disk daemon

### BEGIN INIT INFO
# Provides: 		qdiskd
# Required-Start:	cman
# Required-Stop:	cman
# Default-Start:
# Default-Stop:
# Short-Description:	start/stop quorum disk daemon
# Description:		start/stop quorum disk daemon
### END INIT INFO

# rpm based distros
if [ -d /etc/sysconfig ]; then
	[ -f @INITDDIR@/functions ] && . @INITDDIR@/functions
	[ -f /etc/sysconfig/cluster ] && . /etc/sysconfig/cluster
	[ -f /etc/sysconfig/qdiskd ] && . /etc/sysconfig/qdiskd
	[ -z "$LOCK_FILE" ] && LOCK_FILE="/var/lock/subsys/qdiskd"
	success=success
	failure=failure
	status=status
fi

# deb based distros
if [ -d /etc/default ]; then
	[ -f /etc/default/cluster ] && . /etc/default/cluster
	[ -f /etc/default/qdiskd ] && . /etc/default/qdiskd
	[ -z "$LOCK_FILE" ] && LOCK_FILE="/var/lock/qdiskd"
	success=local_success
	failure=local_failure
	# functions in rpm based distro implements a very complete version
	# of pidof. For now we can live with this.
	status=local_status
fi

local_success()
{
    echo -ne "[  OK  ]\r"
}

local_failure()
{
    echo -ne "[FAILED]\r"
}

local_status()
{
    pid=$(pidof $1 2>/dev/null)
    rtrn=$?
    if [ $rtrn -ne 0 ]; then
        echo "$1 is stopped"
    else
        echo "$1 (pid $pid) is running..."
    fi
    return $rtrn
}

rtrn=1
retries=0

# See how we were called.
case "$1" in
  start)
	echo -n "Starting the Quorum Disk Daemon: "

	$0 status >/dev/null
	if [ $? -eq 0 ]; then
		$success
		echo
		exit 0
	fi

	@SBINDIR@/qdiskd -Q
	rtrn=$?
	if [ $rtrn = 0 ]; then
		touch $LOCK_FILE
		$success
		echo
	else
		$failure
		echo
	fi
		
	;;

  stop)
	echo -n "Stopping the Quorum Disk Daemon: "
	pid="$(pidof qdiskd)"
	while [ -n "$pid" ] && [ $retries -lt 5 ]; do
		kill $pid 2>&1
		pid="$(pidof qdiskd)"
		sleep 1
		((retries++))
	done
	if [ -z "$(pidof qdiskd)" ]; then
		$success
		echo
		rtrn=0
		rm -f $LOCK_FILE
	else
		$failure
		echo
		rtrn=1
	fi
	;;

  restart|reload)
	$0 stop || exit $?
	$0 start 
	rtrn=$?
	;;

  status)
	$status qdiskd
	rtrn=$?
	;;

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

exit $rtrn
