#!/bin/bash
#
# osdial_resource_listen	Listen for server stats for OSDial
#
# Author:	Lott Caskey <lottcaskey@gmail.com>
#
# chkconfig:	345 99 14
#
# description:	Listens for broadcasted servers stats using
#		multicast within the subnet for client discovery
#		and write the output to /opt/osdial/html/admin
# processname:	osdial_resource_listen
#

# Source function library.
. /etc/init.d/functions
[ -f "/etc/sysconfig/osdial" ] && . /etc/sysconfig/osdial

RETVAL=0
proc=osdial_resource_listen
procloop=osdial_resource_listen_loop
pidfile=/var/run/osdial_resource_listen.pid
lockfile=/var/lock/subsys/osdial_resource_listen

[ ! -d "/opt/osdial/html/admin" ] && exit 1

# Run script, if disconnected or SQL drops, wait 30 seconds and try again.
osdial_resource_listen_loop() {
	while true; do
        	/opt/osdial/bin/$proc "$OSDIAL_LABEL" > /dev/null 2>&1
		sleep 30
	done
}
export -f osdial_resource_listen_loop

start() {
	if [ ! -f /var/run/${proc}.pid ]; then
		echo -n $"Starting $proc: "
		$procloop & BCKPID=$!
		RETVAL=$?
		if [ $RETVAL -eq 0 ]; then
			echo $BCKPID > $pidfile
			touch $lockfile
			success
		else
			failure
		fi
		echo
	fi
}

stop() {
	if [ -f /var/run/${proc}.pid ]; then
        	echo -n $"Shutting down $proc: "
		OPPID=`cat $pidfile`
		OCPID=`ps -o pid --no-headers --ppid $OPPID`
		[ -n "$OCPID" -a "$OCPID" -gt 1 ] && kill $OCPID || :
		killproc -p "/var/run/${proc}.pid"
		echo
        	[ $RETVAL -eq 0 ] && rm -f /var/lock/subsys/$proc
	fi
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    status)
        status $proc
        RETVAL=$?
        ;;
    restart)
        stop
        start
        ;;
    *)
        echo $"Usage: $proc {start|stop|status|restart}"
        exit 1
        ;;
esac

exit $RETVAL

