#!/bin/bash
#
# wdmd - watchdog multiplexing daemon
#
# chkconfig: 2345 97 03
# description: starts and stops wdmd daemon
#


### BEGIN INIT INFO
# Provides: wdmd
# Required-Start: $time $syslog
# Required-Stop: $syslog
# Should-Start:
# Should-Stop:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: starts and stops wdmd daemon
# Description: starts and stops wdmd daemon
### END INIT INFO

. /etc/rc.d/init.d/functions

prog="wdmd"
runfile="/run/$prog/$prog.pid"
lockfile="/var/lock/subsys/$prog"
exec="/usr/sbin/$prog"

WDMDGROUP="sanlock"
WDMDOPTS="-G $WDMDGROUP"

[ -f /etc/sysconfig/$prog ] && . /etc/sysconfig/$prog

watchdog_probe() {
	$exec --probe > /dev/null 2>&1
	retval=$?
	return $retval
}

watchdog_check() {
	watchdog_probe
	retval=$?

	if [ $retval -ne 0 ]; then
		show "Loading the softdog kernel module: "
		modprobe softdog && udevadm settle

		watchdog_probe
		retval=$?
		if [ $retval -ne 0 ]; then
			fail
			return 1
		fi
		ok
	fi
}

start() {
	# Check if the service is already running?
	if [ -f $lockfile ]; then
		msg_already_running "wdmd"
		return
	fi

	watchdog_check

	msg_starting "wdmd"
	daemon $prog $WDMDOPTS
	retval=$?
	[ $retval -eq 0 ] && touch $lockfile
	return $retval
}

stop() {
	if [ ! -f $lockfile ]; then
		msg_not_running "wdmd"
		return
	fi
	PID=$(pidofproc -p $runfile $prog)

	killproc -p $runfile $prog -TERM
	retval=$?

	if [ $retval -ne 0 ]; then
		return $retval
	fi

	show "Waiting for %s (%s) to stop:" "$prog" "$PID"

	timeout=10
	while checkpid $PID; do
		sleep 1
		timeout=$((timeout - 1))
		if [ "$timeout" -le 0 ]; then
			fail
			retval=1
			return $retval
		fi
	done

	ok
	rm -f $lockfile
	return $retval
}

condrestart() {
	if [ ! -f $lockfile ]; then
		msg_not_running "wdmd"
		retval=$1
		return $retval
	fi
	stop
	start
}

case "$1" in
	start)
		$1
		;;
	stop)
		$1
		;;
	restart)
		stop
		start
		;;
	watchdog-check)
		watchdog_check
		;;
	force-reload)
		condrestart 7
		;;
	status)
		status --pidfile $runfile wdmd
		;;
	condrestart|try-restart)
		rh_status_q || exit 0
		condrestart 0
		;;
	*)
		msg_usage "$0 {start|stop|status|restart|condrestart|try-restart|force-reload}"
		exit 3
esac
exit $retval
