#! /bin/sh
### BEGIN INIT INFO
# Provides:          darkstat
# Required-Start: $network
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: start darkstat monitoring system at boot time
### END INIT INFO
#
# Please read /usr/share/doc/darkstat/README.Debian

PATH=/bin:/usr/bin:/sbin:/usr/sbin
DAEMON="/usr/sbin/darkstat"
NAME="darkstat"
DESC="darkstat network daemon"
INIT="/etc/darkstat/init.cfg"
HOMEDIR="/var/lib/darkstat"
PIDFILE="/var/run/$NAME.pid"
DIR="/var/lib/darkstat"

test -f $DAEMON || exit 0

test -f $INIT || exit 0

INTERFACE=""
PORT=""
BINDIP=""
LOCAL=""
DNS=""
DB="--import darkstat.db --export darkstat.db"

. $INIT

if [ "$START_DARKSTAT" = "no" ] ; then
  exit 0
fi

test "$START_DARKSTAT" = "yes" || exit 0

case "$1" in
start)
  echo -n "Starting $DESC : $NAME "
  if start-stop-daemon --start --quiet -b --exec $DAEMON -- \
      $INTERFACE \
      $PORT \
      --chroot $DIR \
      --pidfile $PIDFILE \
      $BINDIP \
      $LOCAL \
      $FIP \
      $DNS \
      $SPY \
      $DB; then
      echo "."
  else
      echo " is already running."
  fi
  ;;
stop)
  echo -n "Stopping $DESC : $NAME "
  if start-stop-daemon --quiet --oknodo --stop --name $NAME --pidfile $PIDFILE --retry 30; then
        rm -f $PIDFILE
	echo "."
  else
        echo " is not running."
  fi
  ;;
restart | force-reload)
  echo -n "Restarting $DESC : $NAME "
  if start-stop-daemon --stop --oknodo --name $NAME --pidfile $PIDFILE --retry 30; then
      rm -f $PIDFILE
      echo "stoped."
  else
      echo "$DESC : $NAME is not running"
      rm -f $PIDFILE
  fi
  sleep 1
  start-stop-daemon --start --quiet -b --exec $DAEMON -- \
      $INTERFACE \
      $PORT \
      --chroot $DIR \
      --pidfile $PIDFILE \
      $BINDIP \
      $LOCAL \
      $FIP \
      $DNS \
      $SPY \
      $DB
  echo "."  
  ;;
debug-run)
  echo "$0: Initiating debug run of darkstat..."
  echo "$0: darkstat will be run in verbose mode, all output to forced to"
  echo "$0: stdout. This is not enough to debug failures that only"
  echo "$0: happen in daemon mode."
  echo "$0: You might want to direct output to a file, and tail -f it."
  echo "$0: Type CTRL-C to stop."
  "$0" stop && true
  $DAEMON --debug \
      $INTERFACE \
      $PORT \
      --chroot $DIR \
      $BINDIP \
      $LOCAL \
      $FIP \
      $DNS \
      $SPY 2>&1 && true
  echo "$0: End of service run. Exit status was: $?"
  ;;

*)
  N=/etc/init.d/$NAME
  echo "Usage: $N {start|stop|restart|force-reload|debug-run}" >&2
  exit 1
  ;;
esac

exit 0
