#!/bin/bash

### BEGIN INIT INFO
# Provides:        wdnotifier
# Required-Start:  $network  $syslog
# Required-Stop:   $network  $syslog
# Default-Start:   2 3 4 5
# Default-Stop:    0 1 6
# Short-Description: Start wdnotifier daemon
### END INIT INFO

PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/usr/local/sbin

#. /lib/lsb/init-functions

DAEMON_BASE_NAME=wdnotifier
DAEMON=/usr/local/bin/$DAEMON_BASE_NAME
PIDFILE=/var/run/wdnotifier.pid
SHARE_TRIGGER_DIR=/tmp/share_trigger

createShareTriggers()
{
    mkdir -p $SHARE_TRIGGER_DIR
    for i in `ls -l /shares/ |grep '^d' |awk '{print $9}'`; 
    do 
        touch "${SHARE_TRIGGER_DIR}/.${i}"
    done
}

processPID()
{
    echo `pidof $DAEMON_BASE_NAME`
}

test -x $DAEMON || exit 5

case $1 in
    start)
	echo "Starting $DAEMON_BASE_NAME"
        createShareTriggers
        renice 0 -p $$
	pid=$(processPID)
	if [ "$pid" != "" ]; then
	    echo "$DAEMON_BASE_NAME is already running"
	    exit 1
	fi

	$DAEMON $OPTS
	
        status=$?
	if [ $status = 0 ]; then
	    echo "$DAEMON_BASE_NAME started"
	else
	    echo "$DAEMON_BASE_NAME failed to start"
	fi
        ;;
    stop)
	echo "Stopping $DAEMON_BASE_NAME"
	pid=$(processPID)
	if [ "$pid" = "" ]; then
	    echo "$DAEMON_BASE_NAME is already stopped"
	    exit 1
	fi

	kill $pid
        # Wait a little and remove stale PID file
        sleep 1
	pid=$(processPID)
	if [ "$pid" != "" ]; then
	    echo "$DAEMON_BASE_NAME failed to stop"
	    exit 1
	fi
	
        if [ -f $PIDFILE ]
        then
            rm -f $PIDFILE
        fi
        ;;
    restart|force-reload|reload)
        $0 stop && sleep 5 && $0 start
        ;;
    try-restart)
        if $0 status >/dev/null; then
            $0 restart
        else
            exit 0
        fi
        ;;
    status)
	pid=$(processPID)
	if [ "$pid" != "" ]; then
	    echo "$DAEMON_BASE_NAME is running"
	else
	    echo "$DAEMON_BASE_NAME is not running"
	    exit 1
	fi
	exit 0
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|reload|try-restart|force-reload|status}"
        exit 2
        ;;
esac
