#! /bin/sh
### BEGIN INIT INFO
# Provides:          lbnamed
# Required-Start:    $syslog $remote_fs
# Required-Stop:     $syslog $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Balancing DNS written in Perl
# Description:       Balancig DNS launcher
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC=lbnamed
NAME=lbnamed
DAEMON=/etc/$NAME
PIDFILE=/var/run/$NAME/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
RUN=no

[ -x "$DAEMON" ] || exit 0
[ -r /etc/default/$NAME ] && . /etc/default/$NAME
. /lib/lsb/init-functions

if [ "x$RUN" != "xyes" ]; then
    echo "$DESC disabled."
    echo "Modify $DAEMON and use RUN=yes in /etc/default/$NAME."
    exit 0
fi

do_start()
{
  mkdir -p /var/run/lbnamed 2>/dev/null || :
  chown -R lbnamed:lbnamed /var/run/lbnamed
  start-stop-daemon --start --quiet --pidfile $PIDFILE --chdir /var/lib/lbnamed --exec $DAEMON -- $ARGS || return 2
}

do_stop()
{
  # 1) using SIGKILL to avoid coredumps (there is probably some problem during stop)
  # 2) not providing process name (some problem with the unprivileged user)
  # 3) explicit removal of the pidfile (it isn't removed automatically)
  start-stop-daemon --stop --quiet --signal=KILL --pidfile $PIDFILE && rm -f $PIDFILE
}

case "$1" in
  start)
    [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
    do_start
    case "$?" in
        0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
        2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
    esac
    ;;
  stop)
    [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
    do_stop
    case "$?" in
        0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
        2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
    esac
    ;;
  status)
    status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
    ;;
  restart|force-reload)
    log_daemon_msg "Restarting $DESC" "$NAME"
    do_stop
    case "$?" in
      0|1)
        do_start
        case "$?" in
            0) log_end_msg 0 ;;
            1) log_end_msg 1 ;; # Old process is still running
            *) log_end_msg 1 ;; # Failed to start
        esac
        ;;
      *)
        # Failed to stop
        log_end_msg 1
        ;;
    esac
    ;;
  *)
    echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
    exit 3
    ;;
esac

:
