#!/bin/sh
#
# Nagios	Host/service/network monitoring daemon
#
# chkconfig:	345 85 24
# description:	Host/service/network monitoring daemon which uses snort as NIDS
#

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

# Get network config
. /etc/sysconfig/network

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

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down Nagios
		exit 1
	fi
else
	exit 0
fi

checkconfig() {
	/usr/sbin/nagios -v /etc/nagios/nagios.cfg > /dev/null
	rc=$?
	if [ $rc -gt 0 ]; then
		fail
		nls 'The configuration is broken. See details with %s "checkconfig"' /etc/rc.d/init.d/nagios
	fi
	return $rc
}

start() {
	# Check if the service is already running?
	if [ ! -f /var/lock/subsys/nagios ]; then
		msg_starting Nagios
		checkconfig || exit

		# remove stale cmd pipe (or nagios won't start if it exists)
		rm -f /var/lib/nagios/rw/nagios.cmd
		daemon /usr/sbin/nagios -d /etc/nagios/nagios.cfg </dev/null
		RETVAL=$?
		if [ $RETVAL -eq 0 ]; then
			touch /var/lock/subsys/nagios
		fi
	else
		msg_already_running Nagios
	fi
}

stop() {
	# Stop daemons.
	if [ -f /var/lock/subsys/nagios ]; then
		msg_stopping Nagios
		killproc nagios -TERM
		rm -f /var/lock/subsys/nagios > /dev/null 2>&1
	else
		msg_not_running Nagios
	fi
}

RETVAL=0
# See how we were called.
case "$1" in
start)
	start
	;;
stop)
	stop
	;;
checkconfig|check|configtest)
	/usr/sbin/nagios -v /etc/nagios/nagios.cfg
	exit $?
	;;
reload|force-reload)
	if [ -f /var/lock/subsys/nagios ]; then
		msg_reloading Nagios
		checkconfig || exit

		killproc nagios -HUP
		RETVAL=$?
	else
		msg_not_running Nagios
		exit 7
	fi
	;;
restart)
	msg_reloading Nagios
	checkconfig || exit && started
	stop
	start
	;;
status)
	status nagios
	exit $?
	;;
*)
	msg_usage "$0 {start|stop|restart|reload|force-reload|status|checkconfig}"
	exit 3
esac

exit $RETVAL
