#!/bin/sh
#
# monit		Monitoring daemon
#
# chkconfig:	345 99 01
# description:	Monitoring daemon
#

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

# Get service config
[ -f /etc/sysconfig/monit ] && . /etc/sysconfig/monit

checkconfig() {
	local out
	out=$(/usr/sbin/monit -c /etc/monitrc -t 2>&1)
	ret=$?
	if [ $ret != 0 ]; then
		echo >&2 "$out"
		exit 1
	fi
}

start() {
	# Check if the service is already running?
	if [ -f /var/lock/subsys/monit ] && status monit >/dev/null; then
		msg_already_running monit
		return
	fi

	checkconfig
	msg_starting monit
	daemon --pidfile /var/run/monit.pid /usr/sbin/monit -c /etc/monitrc -s /var/run/monit.state $OPTIONS
	RETVAL=$?
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/monit
}

stop() {
	# Stop daemons.
	if [ ! -f /var/lock/subsys/monit ]; then
		msg_not_running monit
		return
	fi

	msg_stopping monit
	busy
	/usr/sbin/monit -c /etc/monitrc quit
	RETVAL=$?
	[ $RETVAL -eq 0 ] && ok || fail
	rm -f /var/lock/subsys/monit > /dev/null 2>&1
}

reload() {
	if [ ! -f /var/lock/subsys/monit ]; then
		msg_not_running monit
		exit 7
	fi

	checkconfig
	msg_reloading monit
	busy
	/usr/sbin/monit -c /etc/monitrc reload
	RETVAL=$?
	[ $RETVAL -eq 0 ] && ok || fail
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	checkconfig
	stop
	start
	;;
  reload|force-reload)
	reload
	;;
  checkconfig)
	checkconfig
	echo "Config check OK"
	;;
  status)
	status monit
	RETVAL=$?
	# monit status is unreliable (always 0). so use rc-scripts status code
	monit -c /etc/monitrc status
	exit $RETVAL
	;;
  *)
	msg_usage "$0 {start|stop|restart|reload|force-reload|checkconfig|status}"
	exit 3
esac

exit $RETVAL
