#!/bin/bash

# daemoncheck.sh v0.1
# simple daemon alive check by G. Nickels <gsn@kernel-oops.de>

DAEMON="sendmail"                     # daemon binary as listed in ps output 
PIDFILE="/var/run/sendmail.pid"       # path to pid file
STARTCMD="/etc/init.d/sendmail start" # daemon start command
OUTPREFIX="SENDMAIL"                  # output prefix for failure notices


#############################################################
### don't touch unless you really know what you are doing ###
#############################################################

PIDNO=$(cat $PIDFILE|grep -v $DAEMON 2>&1)
if [ "$PIDNO" == "" ]; then
 echo "$OUTPREFIX: no pid file found..."
 if [ $(ps auxww|grep $DAEMON|grep -v grep|wc -l) -gt 0 ]; then
  echo "$OUTPREFIX: killing stale processes..."
  killall -9 $DAEMON
 fi
 echo "$OUTPREFIX: starting daemon..."
 $STARTCMD
else
 RUNPROCS=$(ps auxww|grep $DAEMON|awk '{ print $2 }'|grep $PIDNO|wc -l)
 if [ $RUNPROCS -lt 1 ]; then
  echo "$OUTPREFIX: stale pid file found, deleting..."
  rm $PIDFILE
  if [ $(ps auxww|grep $DAEMON|grep -v grep|wc -l) -gt 0 ]; then
   echo "$OUTPREFIX: killing stale processes..."
   killall -9 $DAEMON
  fi
  echo "$OUTPREFIX: starting daemon..."
  $STARTCMD
 fi
fi
exit 0

