#! /bin/sh
### BEGIN INIT INFO
# Provides:          ardj-server
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $local_fs $remote_fs $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: ardj web server
### END INIT INFO

PATH=/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/bin
DESC="ardj-server"
NAME=ardj
DAEMON_ARGS="serve"
PIDFILE=/var/run/ardj-server.pid
SCRIPTNAME=/etc/init.d/ardj-server

# Support local installation using pip.
for tmp in /usr/locla/bin/ardj /usr/bin/ardj; do
    if [ -x $tmp ]; then
        DAEMON=$tmp
        break
    fi
done

. /lib/lsb/init-functions

# Exit if the package is not installed
[ -n "$DAEMON" ] || exit 0

# Exit if there's no config file.
[ -f /etc/ardj.yaml ] || exit 0

case "$1" in
    start)
        log_daemon_msg "Starting $DESC" "$NAME"
        start-stop-daemon --start --quiet --oknodo --pidfile $PIDFILE --make-pidfile \
            --background --chuid ardj --exec $DAEMON -- $DAEMON_ARGS
        log_end_msg $?
        ;;
    stop)
        log_daemon_msg "Stopping $DESC" "$NAME"
        start-stop-daemon --stop --quiet --oknodo --retry=TERM/15/KILL/5 --pidfile $PIDFILE \
            --name $NAME
        log_end_msg $?
        rm -f $PIDFILE
        ;;
    status)
        pidofproc -p $PIDFILE $DAEMON >/dev/null
        status=$?
        
        if [ $status -eq 0 ]; then
            log_success_msg "$DESC is running"
        else
            log_failure_msg "$DESC is not running"
        fi
        exit $status
        ;;
    reload|force-reload)
        log_daemon_msg "Reloading $DESC configuration..."
        start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME
        log_end_msg 0
        ;;
    restart)
        $0 stop
        sleep 1
        $0 start
        ;;
    *)
        echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload|status}"
        exit 1
        ;;
esac

exit 0
