#!/bin/sh
### BEGIN INIT INFO
# Provides:          skeleton
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      S 0 1 6
# Short-Description: initscript for dspam
# Description:       dspam is a scalable, fast and statistical anti-spam filter
### END INIT INFO
#
# Author:	Matthijs Mohlmann <matthijs@cacholong.nl>.
#
# Based on the init script of pdns-recursor
#

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DESC="DSPAM Statistical anti-spam filter"
NAME=dspam
DAEMON=/usr/bin/$NAME
PIDFILE=/var/run/dspam/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

# Gracefully exit if the package has been removed.
test -x $DAEMON || exit 0

# Read config file if it is present.
if [ -r /etc/default/$NAME ]; then
	. /etc/default/$NAME
fi

OPTIONS="--daemon $OPTIONS"

# Start the daemon
d_start() {
# Return
#  0 if daemon has been started
#  1 if daemon was already running
#  2 if daemon could not be started
  start-stop-daemon --start --quiet --pidfile $PIDFILE --chuid $USER --exec $DAEMON --test > /dev/null || return 1
  start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- $OPTIONS || return 2
}

# Stop the daemon
d_stop() {
# Return
#  0 if daemon has been stopped
#  1 if daemon was already stopped
#  2 if daemon could not be stopped
#  other if a failure occured
  start-stop-daemon --stop --quiet --retry=TERM/5/KILL/5 --pidfile $PIDFILE --name $NAME
  RETVAL="$?"
  [ "$RETVAL" = 2 ] && return 2
  start-stop-daemon --stop --quiet --oknodo --retry=KILL/5 --exec $DAEMON
  [ "$?" = 2 ] && return 2
  rm -f $PIDFILE
  return "$RETVAL"
}

case "$1" in
  start)
    if [ "$START" != "yes" ]; then
      echo "Not starting $DESC -- disabled."
      exit 0
    fi
    echo -n "Starting $DESC: $NAME"
    d_start
    case "$?" in
      0)
        echo "."
        exit 0
        ;;
      1)
        echo " (already running)."
        exit 0
        ;;
      *)
        echo " (failed)."
        exit 1
        ;;
    esac
    ;;
  stop)
    # Always try to stop the daemon.
    echo -n "Stopping $DESC: $NAME"
    d_stop
    case "$?" in
      0)
        echo "."
        exit 0
        ;;
      1)
        echo " (not running)."
        exit 0
        ;;
      *)
        echo " (failed)."
        exit 1
    esac
    ;;
  restart|force-reload)
    if [ "$START" != "yes" ]; then
      $0 stop
      exit 0
    fi
    echo -n "Restarting $DESC: $NAME"
    d_stop
    case "$?" in
      0|1)
        d_start
        case "$?" in
          0)
            echo "."
            exit 0
            ;;
          1)
            echo " (failed -- old process still running)."
            exit 1
            ;;
          *)
            echo " (failed to start)."
            exit 1
            ;;
        esac
        ;;
      *)
        echo " (failed to stop)."
        exit 1
        ;;
    esac
    ;;
  *)
    echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
    exit 1
    ;;
esac

exit 0

