#! /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

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/clamd
NAME="clamd"
DESC="clamav daemon"
CLAMAVCONF=/etc/clamav/clamav.conf
THEPIDFILE="`grep ^PidFile $CLAMAVCONF | sed -e 's/PidFile //'`"

SUPERVISOR=/usr/bin/daemon
SUPERVISORPIDFILE="/var/run/clamav/daemon-clamd.pid"
SUPERVISORARGS="--name=$NAME --respawn $DAEMON -F $SUPERVISORPIDFILE"

test -f $DAEMON || exit 0

[ -f /etc/default/clamav-daemon ] && . /etc/default/clamav-daemon

set -e

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 $SUPERVISOR not found"
     exit 0
  else
     RUN_SUPERVISED=1
  fi
fi

case "$1" in
  start)
  echo -n "Starting $DESC: $NAME"
  if [ -z "$RUN_SUPERVISED" ] ; then
    start-stop-daemon --oknodo -S -x $DAEMON
  else 
    echo -n "(supervised)"
    $SUPERVISOR $SUPERVISORARGS
  fi
  echo "."
  ;;
  stop)
  echo -n "Stopping $DESC: $NAME"
  if [ -z "$RUN_SUPERVISED" ] ; then
    start-stop-daemon --oknodo -K -q -R 30 -p $THEPIDFILE 
  else
    echo -n "(supervised)"
    start-stop-daemon --oknodo -K -q -R 30 -p $SUPERVISORPIDFILE
  fi
  echo "."
  ;;
  restart|force-reload)
  echo -n "Restarting $DESC: $NAME"
  if [ -z "$RUN_SUPERVISED" ] ; then
    start-stop-daemon --oknodo -K -q -R 30 -p $THEPIDFILE
    start-stop-daemon --oknodo -S -x $DAEMON
  else
    echo -n "(supervised)"
    start-stop-daemon --oknodo -K -q -p $SUPERVISORPIDFILE
    sleep 2
    $SUPERVISOR $SUPERVISORARGS
  fi
  echo "."
  ;;
  reload)
  echo -n "Reloading $DESC: $NAME"
  start-stop-daemon -o -K -q -s 1 -p $THEPIDFILE -x $DAEMON
  echo "."
  ;;
  *)
  echo "Usage: $0 {start|stop|reload|restart|force-reload}" >&2
  exit 1
  ;;
esac

exit 0
