#!/bin/sh
### BEGIN INIT INFO
# Provides:          noris-identd 
# Required-Start:    $local_fs $network $time $remote_fs
# Required-Stop:     $local_fs $network $time $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Starting noris identd 
# Description:       Starting an identd configured individually for noris
#  ident daemon.
### END INIT INFO#
### BEGIN INIT INFO
# Provides:          noris-identd 
# Required-Start:    $local_fs $network $time $remote_fs
# Required-Stop:     $local_fs $network $time $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Starting noris identd 
# Description:       Starting an identd configured individually for noris
#  ident daemon.
### END INIT INFO#

# start/stop script for noris identd server
# Copyright (C) 2010 noris network AG. Michael Radziej <mir@noris.de>, Micha Krause <micha@noris.de>

set -e
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
. /etc/default/rcS

BIN=/usr/sbin/noris-identd
PIDFILE=/var/run/noris-identd.pid

# Gracefully exit if the package has been removed.
test -r "$BIN" || exit 0

set +e


# Functions for start/stop
d_status() {
    start-stop-daemon --stop --pidfile "$PIDFILE" --user root -q --signal 0 >/dev/null
}

d_start() {
    touch "$PIDFILE" || return 1
    start-stop-daemon --quiet \
        -p "$PIDFILE" \
        --background \
        --make-pidfile \
        --chdir "/" \
        --exec "$BIN" \
        --start \
    || return 1
    sleep 1
    d_status
}

d_stop() {
    start-stop-daemon --stop --user root --quiet --oknodo --pidfile "$PIDFILE"
}

end_msg() {
    [ -z "$1" ] && return 1
    if [ "$1" -eq 0 ]
    then
        echo .
    else
        echo " FAILED."
    fi
}


case "$1" in
  start)
        echo -n "Starting noris-identd"
        d_status && echo " FAILED: Already running." && exit 1
        d_start
        ES=$?
        end_msg $ES
        exit $ES
        ;;

  stop)
    echo -n "Stopping noris-identd daemon"
    d_stop
    ES=$?
    rm -f "$PIDFILE"
    end_msg $ES
    ;;

  reload)
    echo "Reloading noris-identd FAILED: reload not implemented. Use restart."
    exit 1
    ;;

  restart|force-reload)
        echo -n "Restarting noris-identd"
        d_stop
        sleep 1
        if d_status
        then
            echo " FAILED: Still running after stop."
            exit 1
        fi
        d_start
        end_msg $?
        ;;

  status)
    echo -n "noris-identd ... "
    if d_status
    then
            echo running
    else
            echo NOT running
            exit 1
    fi
    ;;

  *)
    echo "Usage: /etc/init.d/noris-identd {start|stop|restart|force-reload|status}"
    exit 1
    ;;
esac
exit 0
