#! /bin/sh
#		Written by Miquel van Smoorenburg <miquels@cistron.nl>.
#		Modified for Debian GNU/Linux
#		by Ian Murdock <imurdock@gnu.ai.mit.edu>.
#               Clamav version by Magnus Ekdahl <magnus@debian.org>
#
# Version:	1.9 2003-07-20 magnus@debian.org

set -e

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/clamd
NAME="clamd"
DESC="ClamAV daemon"
CLAMAVCONF=/etc/clamav/clamd.conf
SUPERVISOR=/usr/bin/daemon
SUPERVISORNAME=daemon
SUPERVISORPIDFILE="/var/run/clamav/daemon-clamd.pid"
SUPERVISORARGS="--name=$NAME --respawn $DAEMON -F $SUPERVISORPIDFILE"

[ -x "$DAEMON" ] || exit 0
[ -r /etc/default/clamav-daemon ] && . /etc/default/clamav-daemon

if [ ! -f "$CLAMAVCONF" ]; then
  echo "There is no configuration file for Clamav."
  echo "Please either dpkg-reconfigure $DESC, or copy the example from"
  echo "/usr/share/doc/clamav-daemon/examples/ to $CLAMAVCONF and run"
  echo "'/etc/init.d/clamav-daemon start'"
  exit 0;
fi

if grep -q "^Example" $CLAMAVCONF; then
  echo "Clamav is not configured."
  echo "Please edit $CLAMAVCONF and run  '/etc/init.d/clamav-daemon start'"
  exit 0
fi

if grep -q "^Foreground" $CLAMAVCONF; then
  if [ ! -x "$SUPERVISOR" ] ; then
     echo "Foreground specified, but $SUPERVISORNAME not found"
     exit 0
  else
     RUN_SUPERVISED=1
  fi
fi

THEPIDFILE="`grep ^PidFile $CLAMAVCONF | awk '{print $2}'`"

if [ -z "$RUN_SUPERVISED" ]; then
  [ -e "$THEPIDFILE" ] && PID=`cat $THEPIDFILE`
else
  [ -e "$SUPERVISORPIDFILE" ] && PID=`cat $SUPERVISORPIDFILE`
fi

[ "$PID" = '1' ] && unset PID

case "$1" in
  start)
  echo -n "Starting $DESC: "
  if [ -z "$RUN_SUPERVISED" ] ; then
    start-stop-daemon --oknodo -S -x $DAEMON
  else 
    echo -n "(supervised) "
    $SUPERVISOR $SUPERVISORARGS
  fi
  echo "$NAME"
  ;;
  stop)
  echo -n "Stopping $DESC: "
  if [ -n "$PID" ]; then
    kill -15 -"$PID"
    sleep 1
    if kill -0 "$PID" 2>/dev/null; then
      echo -n "Waiting . "
      cnt=0
      while kill -0 "$PID" 2>/dev/null; do
        cnt=`expr "$cnt" + 1`
        if [ "$cnt" -gt 60 ]; then
          echo -n " Failed.. "
          kill -9 -"$PID"
          break
        fi
        sleep 2
        echo -n ". "
      done
    fi
  else
    if [ -z "$RUN_SUPERVISED" ] ; then
      start-stop-daemon -o -K -q -R 30 -p $THEPIDFILE
    else
      echo -n "(supervised) "
      start-stop-daemon -o -K -q -R 30 -p $SUPERVISORPIDFILE
    fi
  fi
  echo "$NAME"
  ;;
  restart|force-reload)
  $0 stop
  $0 start
  ;;
  *)
  echo "Usage: $0 {start|stop|restart|force-reload}" >&2
  exit 1
  ;;
esac

exit 0
