#!/bin/sh
#
#  radwatch
#
#    Script to make sure radiusd is always running
#
#               colin@grandecom.com
#

RWLOG="/var/log/radwatch.log"		# Use "/dev/null" for no logging
RWCMD="/usr/local/sbin/radiusd -y"	# Path to radiusd + run-time arguments
RWRCP="foo@bar.com"			# Recipient for alerts.  Comment out to disable
RWINT=10				# Time in seconds between process list polls

UNAME=`uname`

case "$UNAME" in
  Linux)
    OS="xbsd"
    ;;
  FreeBSD)
    OS="xbsd"
    ;;
  OpenBSD)
    OS="xbsd"
    ;;
  NetBSD)
    OS="xbsd"
    ;;
  SunOS)
    OS="sysv"
    ;;
  *)
    OS="sysv"
    ;;
esac

(
while :
do

  if [ "$OS" = "xbsd" ]; then
    PIDS=`ps ax | grep -v grep | grep radiusd | awk '{print $1}'`
  fi

  if [ "$OS" = "sysv" ]; then
    PIDS=`ps -eaf | grep -v grep | grep radiusd | awk '{print $2}'`
  fi

  if [ "$PIDS" != "" ]; then
    COUNT=`echo $PIDS | wc -w | tr -d " "`
  else
    COUNT=0
  fi

  if [ $COUNT -lt 2 ]; then
    STAMP=`date "+%m/%d/%y %H:%M:%S"`
    ALERT="$COUNT processes.  Restarting ICRADIUS."
    echo "$STAMP	`basename $0`:  $ALERT" >> $RWLOG
    if [ "$RWRCP" != "" ]; then
      echo "`basename $0`:  $ALERT" | mail -s "ICRADIUS Restarted" $RWRCP
    fi
    kill $PIDS 2>/dev/null; $RWCMD
  fi
  
  sleep $RWINT

done
) &
