#! /bin/sh
#
# Author:	Matthijs Mohlmann <matthijs@cacholong.nl>.
# 
# Thanks to:
# Thomas Hood <jdthood@aglu.demon.nl>
#
# initscript for PowerDNS recursor

set +e # Don't exit on error status

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DESC="PowerDNS recursor"
NAME=pdns_recursor
DAEMON=/usr/sbin/$NAME
PIDFILE=/var/run/$NAME.pid

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

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

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 --exec $DAEMON --test > /dev/null || return 1
  start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- --daemon || return 2
}

start_resolvconf() {
  if [ -x /sbin/resolvconf ]; then
    echo "nameserver 127.0.0.1" | /sbin/resolvconf -a lo.pdns-recursor
  fi
  return 0
}

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=HUP/30/TERM/5/KILL/5 --pidfile $PIDFILE --name $NAME
  RETVAL="$?"
  [ "$RETVAL" = 2 ] && return 2
  start-stop-daemon --stop --quiet --oknodo --retry=HUP/30/KILL/5 --exec $DAEMON
  [ "$?" = 2 ] && return 2
  rm -f $PIDFILE
  return "$RETVAL"
}

stop_resolvconf() {
  if [ -x /sbin/resolvconf ]; then
    /sbin/resolvconf -d lo.pdns-recursor
  fi
  return 0
}

case "$1" in
  start)
    if [ "$START" != "yes" ]; then
      echo "Not starting $DESC -- disabled."
      exit 0
    fi
    echo -n "Starting $DESC: "
    start
    case "$?" in
      0)
        echo "."
        start_resolvconf
        exit 0
        ;;
      1)
        echo " (already running)."
        exit 0
        ;;
      *)
        echo " (failed)."
        exit 1
        ;;
    esac
  ;;
  stop)
    stop_resolvconf
    echo -n "Stopping $DESC: "
    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: "
    stop
    case "$?" in
      0|1)
        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: $0 {start|stop|restart|force-reload}" >&2
    exit 3
  ;;
esac

exit 0

