#!/bin/sh
# edit /etc/default/clamav-milter for options

set -e

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/clamav-milter
DESC="Sendmail milter plugin for ClamAV"
BASENAME=clamav-milter
CLAMAVCONF=/etc/clamav/clamd.conf
DEFAULT=/etc/default/clamav-milter
OPTIONS="-dq"
SUPERVISOR=/usr/bin/daemon
SUPERVISORPIDFILE="/var/run/clamav/daemon-clamav-milter.pid"
SUPERVISORARGS="-F $SUPERVISORPIDFILE --name=$BASENAME --respawn"

[ -x "$DAEMON" ] || exit 0
[ -r "$CLAMAVCONF" ] || exit 0
[ -r "$DEFAULT" ] && . $DEFAULT
[ -z "$PIDFILE" ] && PIDFILE=/var/run/clamav/clamav-milter.pid
[ -z "$SOCKET" ] && SOCKET=local:/var/run/clamav/clamav-milter.ctl

case "$SOCKET" in
  /*)
  SOCKET_PATH="$SOCKET"
  SOCKET="local:$SOCKET"
  ;;
  *)
  SOCKET_PATH=`echo $SOCKET | sed -e s/local\://`
  # If the socket is type inet: we don't care - we can't rm -f that later :)
  ;;
esac

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

if [ -z "$RUN_SUPERVISED" ] ; then
  [ -e "$PIDFILE" ] && PID=`sed 's/[^0-9]//g' $PIDFILE`
else
  [ -e "$SUPERVISORPIDFILE" ] && PID=`sed 's/[^0-9]//g' $SUPERVISORPIDFILE`
fi

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

case "$1" in
  start)
  echo -n "Starting $DESC: "
  if [ -z "$RUN_SUPERVISED" ] ; then
    start-stop-daemon -S -x $DAEMON -o -- $OPTIONS --pidfile $PIDFILE $SOCKET
  else
    echo -n "(supervised) "
    $SUPERVISOR $SUPERVISORARGS -X "$SUPERVISOR_EXEC"
  fi
  echo "$BASENAME"
  ;;
  stop)
  echo -n "Stopping $DESC: "
  if [ -n "$PID" ]; then
    kill -15 -"$PID" 2>/dev/null || true
    sleep 2
    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 15 ]; then
          echo -n " Failed.. "
          kill -9 -"$PID"
          break
        fi
        sleep 2
        echo -n ". "
      done
    fi
  else
    if [ -z "$RUN_SUPERVISED" ] ; then
      start-stop-daemon -q -K -o -R 30 -p $PIDFILE $DAEMON
    else
      echo -n "(supervised) "
      start-stop-daemon -q -K -o -R 30 -p $SUPERVISORPIDFILE
    fi
  fi
  [ -e "$SOCKET_PATH" ] && rm -f $SOCKET_PATH
  [ -e "$PIDFILE" ] && rm -f $PIDFILE
  echo "$BASENAME"
  ;;
  force-reload | restart)
  $0 stop
  $0 start
  ;;
  *)
  echo "Usage: $0 {start|stop|restart|force-reload}" >&2
  exit 1
  ;;
esac

exit 0
