#!/bin/sh
#
### BEGIN INIT INFO
# Provides:        debpool
# Required-Start:  $remote_fs
# Required-Stop:   $remote_fs
# Default-Start:   2 3 4 5
# Default-Stop:    0 1 6
# Short-Description: Start Debian package archiver
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/debpool
NAME=debpool
DEFAULT=/etc/default/$NAME
DESC="Debian package archiver"
test -x $DAEMON || exit 0

. /lib/lsb/init-functions

# Set these in /etc/default/debpool
ENABLED=0
USER=""
OPTIONS=""

# Include debpool defaults if available
if [ -f /etc/default/debpool ]; then
        . /etc/default/debpool
fi

if [ "$ENABLED" = "0" ]; then
        test "$1" = "start" && echo "Not starting $DESC; disabled in $DEFAULT."
        exit 0
fi

eval USERHOME=~$USER
if [ "${USERHOME#/}" = "${USERHOME}" ]; then
    log_failure_msg "$NAME: The user '$USER' specified in $DEFAULT is invalid."
    exit 1
fi

PIDFILE=$({ head -n 80 $DAEMON; echo 'print $Options{"lock_file"};'; } \
    | HOME=$USERHOME perl - $OPTIONS) \
    || { log_failure_msg "$NAME: configuration is broken."; exit 1; }

if [ -n "$USER" ]; then
    CHUID="--chuid $USER"
fi

case "$1" in
    start)
        log_daemon_msg "Starting $DESC" "$NAME"
        start-stop-daemon --start --quiet --pidfile $PIDFILE \
                --exec $DAEMON $CHUID -- --daemon $OPTIONS
        log_end_msg $?
        ;;
    stop)
        log_daemon_msg "Stopping $DESC" "$NAME"
        start-stop-daemon --stop --quiet --pidfile $PIDFILE \
                --oknodo --exec $DAEMON
        log_end_msg $?
        ;;
    force-reload)
        # check wether $DAEMON is running. If so, restart
        start-stop-daemon --stop --test --quiet --pidfile \
                $PIDFILE --exec $DAEMON \
        && exec $0 restart \
        exit 0
        ;;
    restart)
        log_daemon_msg "Restarting $DESC" "$NAME"
        start-stop-daemon --stop --quiet --pidfile $PIDFILE \
                --oknodo --exec $DAEMON
        sleep 1
        start-stop-daemon --start --quiet --pidfile $PIDFILE \
                --exec $DAEMON $CHUID -- --daemon $OPTIONS
        log_end_msg $?
        ;;
    *)
        N=/etc/init.d/$NAME
        # echo "Usage: $N {start|stop|restart|reload|force-reload}" >&2
        echo "Usage: $N {start|stop|restart|force-reload}" >&2
        exit 2
        ;;
esac

exit 0
