#! /bin/bash
#
# RBNA		Start/Stop the Royal Bank Nagios Agent daemon.
#
# chkconfig: 2345 95 65
# description: RBNA (Royal Bank Nagios Agent) manages and maintains the \
#	       NRPE and Nagios environment on a server.  It keeps all \
#	       configuration and plugin content in sync with a master web service. \
# processname: RBNA
# config: /opt/nagios/RBNA/etc/RBNA.conf
# pidfile: /var/run/RBNA.pid

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

# See how we were called.

prog=RBNA
RBNA="/opt/nagios/RBNA/bin/RBNA.pl"
RBNAPID="/opt/nagios/RBNA/etc/RBNA.pid"

start() {
	echo -n $"Starting $prog: "
	if [ -e /var/lock/subsys/RBNA ]; then
	    if [ -e $RBNAPID ] && [ -e /proc/`cat $RBNAPID` ]; then
		echo -n $"cannot start RBNA: already running.";
		failure $"cannot start RBNA: already running.";
		echo
		return 1
	    fi
	fi
	daemon $RBNA start --silent
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && touch /var/lock/subsys/RBNA && ln -sf $RBNAPID /var/run/RBNA.pid;
	return $RETVAL
}

stop() {
	echo -n $"Stopping $prog: "
	if [ ! -e /var/lock/subsys/RBNA ]; then
	    echo -n $"cannot stop RBNA: is not running."
	    failure $"cannot stop RBNA: is not running."
	    echo
	    return 1;
	fi
	killproc RBNA
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/RBNA && rm -f /var/run/RBNA.pid;
	return $RETVAL
}

rhstatus() {

	$RBNA status --silent;
	
	if [ $? == 0 ]; then
		read pid < /var/run/${prog}.pid
		echo $"${prog} (pid $pid) is running..."
		return 0
	fi

	# Next try "/var/run/*.pid" files
	if [ -f /var/run/${prog}.pid ] ; then
		read pid < /var/run/${prog}.pid
		if [ -n "$pid" ]; then
			echo $"${prog} dead but pid file exists"
			return 1
		fi
	fi
	# See if /var/lock/subsys/${prog} exists
	if [ -f /var/lock/subsys/${prog} ]; then
		echo $"${prog} dead but subsys locked"
		return 2
	fi

	echo $"${prog} is stopped"
	return 3
}

restart() {
	stop
	start
}

case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	restart
	;;
  status)
	rhstatus
	;;
  *)
	echo $"Usage: $0 {start|stop|status}"
	exit 1
esac
