#!/bin/sh
#
# Author: Michael Conrad <do5mc@friggleware.de>
#

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/bin:/usr/sbin:/usr/bin

NAME="aprs4r"
DESC="APRS4R Watchdog"

if [ -z "$APRS4R_DAEMON" ]; then
  APRS4R_DAEMON=/usr/bin/aprs4r
fi

if [ -z "$APRS4R_DEFAULT" ]; then 
  APRS4R_DEFAULT=/etc/default/aprs4r
fi

if [ -z "$APRS4R_LOG" ]; then 
  APRS4R_LOG=/var/log/aprs4r
fi

LOG_FILE=$APRS4R_LOG/watchdog.log

if [ -z "$APRS4R_PID" ]; then
  APRS4R_PID=/var/run/aprs4r.pid
fi

# Exit if the package is not installed
[ -x "$APRS4R_DAEMON" ] || exit 0

# Read configuration variable file if it is present
[ -r "$APRS4R_DEFAULT" ] && . $APRS4R_DEFAULT


function log_log ()
{
  timestamp_date=`date +%Y-%m-%d`
  timestamp_time=`date +%H:%M:%S`

  echo "$timestamp_date $timestamp_time $*"
}


function log_info ()
{
  log_log INFO $1
}

function log_error ()
{
  log_log ERROR $1
}

function log_warn ()
{
  log_log WARN $1
}


if [ "$START_DAEMON" != "true" ]; then
  echo "$APRS4R_DAEMON disabled (see $APRS4R_DEFAULT)"
  exit 0 
fi


function 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
      log_info "$NAME is running (id $PID)"
      status=0
    else 
      log_warn "$APRS4R_PID exists, but $NAME is not running"
      status=1
    fi 
  else
    log_warn "$NAME is not running"
    status=2
  fi
  
  return $status
}


# main control loop
while /bin/true; do

  check_pid $APRS4R_PID

  if [ $? -ne 0 ]; then
    log_info "ohhh"
  else
    log_info "keep cool, all okay"
  fi

  sleep $WATCHDOG_TIMEOUT

done



