#!/bin/ksh
###################################################################
#	keep_running
#
#	Script to ensure that relevant daemons are always alive
#
###################################################################

exec > /dev/console 2>&1

CONFIG_FILE=/usr/local/etc/keep_running.conf

ARG0=`basename "$0"`

SLEEP_TIME=30

# Is this a BSD or SYSV style 'ps'
if ps -p $$ > /dev/null 2>&1
then
    SYSV_STYLE_PS=y
    PS='ps -p'
else
    SYSV_STYLE_PS=n
    PS='ps '
fi

is_running()
{
    #  Arg1:	file containing PID
    #  Arg2:	strings to grep for in ps listing

    PID=`cat "$1"`					|| return 1

    test "1" -lt "$PID"					|| return 1

    kill -0 $PID 2> /dev/null				|| return 1

    $PS $PID | grep "$2" >/dev/null
}


while true
do

    if [ ! -f "$CONFIG_FILE" ]
    then
	echo "$0: cannot find Config File :'$CONFIG_FILE'" >&2
	logger -p daemon.error -t "$ARG0" "cannot find Config File :'$CONFIG_FILE'" 
	sleep $SLEEP_TIME 2>/dev/null
	continue
    fi

    cat "$CONFIG_FILE" |
     sed -e 's/[ 	]*#.*//' -e '/^[ 	]*$/d' |
      while read pid_file ps_grep start_cmd
      do
	if is_running "$pid_file" "$ps_grep"
	then
	    : Daemon is running - This is good !
	else
	    (
		eval "$start_cmd"
		sleep 4
		logger -p daemon.warning -t "$ARG0" "Restarting daemon '$ps_grep'"
	    ) &
	fi
      done

    sleep $SLEEP_TIME 2>/dev/null
done
