#!/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=$(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 ]; then
		checkconfig
		msg_starting monit
		daemon /usr/sbin/monit -c /etc/monitrc -l syslog -d 60 -s /var/run/monit.state
		RETVAL=$?
		[ $RETVAL -eq 0 ] && touch /var/lock/subsys/monit
	else
		msg_already_running monit
	fi
}

stop() {
	# Stop daemons.
	if [ -f /var/lock/subsys/monit ]; then
		msg_stopping monit
		daemon --waitforname monit --waitfortime 10 monit -c /etc/monitrc quit
		rm -f /var/lock/subsys/monit > /dev/null 2>&1
	else
		msg_not_running monit
	fi
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
  	start
	;;
  stop)
  	stop
	;;
  restart)
	checkconfig
	stop
	start
	;;
  reload|force-reload)
	if [ -f /var/lock/subsys/monit ]; then
		checkconfig
		msg_reloading monit
		daemon /usr/sbin/monit -c /etc/monitrc reload
		RETVAL=$?
	else
		msg_not_running monit
		exit 7
	fi
	;;
  checkconfig)
	checkconfig
	echo "Config check OK"
	;;
  status)
	status monit
	monit -c /etc/monitrc status
	exit $?
	;;
  *)
	msg_usage "$0 {start|stop|restart|reload|force-reload|checkconfig|status}"
	exit 3
esac

exit $RETVAL
