#!/bin/sh
#
# Author: Michael Conrad <do5mc at aprs4r.org>
#

APRS4R_NAME=aprs4r
APRS4R_DESC="APRS4R"

# set daemon path
[ -z "$APRS4R_DAEMON" ] && APRS4R_DAEMON=/usr/bin/aprs4r

# set default file
[ -z "$APRS4R_DEFAULT" ] && APRS4R_DEFAULT=/etc/default/aprs4r

# set aprs4r pid file
[ -z "$APRS4R_PID" ] && APRS4R_PID=/var/run/aprs4r.pid

# set watchdog pid file
[ -z "$APRS4R_WATCHDOG_PID" ] && APRS4R_WATCHDOG_PID=/var/run/aprs4r_watchdog.pid

# set etc path
[ -z "$APRS4R_ETC" ] && APRS4R_ETC=/etc/aprs4r

# set log path 
[ -z "$APRS4R_LOG" ] && APRS4R_LOG=/var/log/aprs4r

LOG_FILE=$APRS4R_LOG/aprs4r-watchdog.log


write_log() 
{ 
    timestamp=`date +'%Y-%m-%d %H:%M:%S'`

    echo "[$1] $timestamp: $2" >> $LOG_FILE 
}


check_daemon() 
{
    # Exit if the package is not installed
    if [ ! -f "$APRS4R_DAEMON" ]; then
	write_log "ERROR", "$APRS4R_DAEMON not installed"
	exit 4
    fi

    if [ ! -x "$APRS4R_DAEMON" ]; then 
	write_log "ERROR", "$APRS4R_DAEMON not an executable"
	exit 5
    fi
}


load_default() { 

    # read configuration variable file if it is present
    if [ -r "$APRS4R_DEFAULT" ]; then 
	. $APRS4R_DEFAULT
    fi

    # set default timeout, if missing
    if [ -z "$TIMEOUT" ]; then 
	TIMEOUT=60
	write_log "WARN", "no value for TIMEOUT, using default value ($TIMEOUT)"
    fi

}


check_pid ()
{
    status=0
    PID_FILE=$1
    
    if [ -s "$PID_FILE" ]; then

	PID=`cat "$PID_FILE"`

	kill -0 "$PID" 2> /dev/null
	if [ $? -eq 0 ]; then
	    # write_log "INFO", "$APRS4R_NAME is running (id $PID)"
	    return 0
	else 
	    write_log "WARN", "$APRS4R_PID exists, but $APRS4R_NAME is not running"
	    return 4
	fi 
    else
	write_log "WARN", "$APRS4R_NAME is not running"
	return 8
    fi
  
    return $status
}


check_daemon

load_default


# check for aprs4r daemon
if [ "$START_DAEMON" != "true" ]; then
    write_log "WARN", "$APRS4R_DAEMON disabled (see $APRS4R_DEFAULT)"
    exit 0 
fi

# write own pid
echo $$ > $APRS4R_WATCHDOG_PID

PROFILE_FILE=$APRS4R_ETC/$PROFILE

export APRS4R_WATCHDOG_RUN=0

sleep 10 

if [ ! -z "$ULIMIT" ]; then
    export APRS4R_ULIMIT=$ULIMIT
fi

# main control loop
while /bin/true; do
    
    check_pid $APRS4R_PID
    
    if [ $? -ne 0 ]; then

	export APRS4R_WATCHDOG_RUN=$(($APRS4R_WATCHDOG_RUN + 1))

	write_log "WARN", "restarting $APRS4R_DAEMON"
	$APRS4R_DAEMON $PROFILE_FILE &
	
	# wait 5 seconds after restart
	sleep 5
    fi

    sleep $TIMEOUT
    
done

