#!/bin/sh
### BEGIN INIT INFO
# Provides:          yubihsm-connector
# Required-Start:    $local_fs $network $named $time $syslog
# Required-Stop:     $local_fs $network $named $time $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the yubihsm-connector
# Description:       starts yubihsm-connector using start-stop-daemon
### END INIT INFO

DESC="yubihsm-connector"
NAME=yubihsm-connector
DAEMON=/usr/bin/yubihsm-connector

DAEMONOPTS="-c /etc/yubihsm-connector.yaml"
DAEMONUSER=yubihsm-connector
PIDFILE=/var/run/$NAME.pid
LOGFILE=/var/log/$NAME.log
STOP_SCHEDULE="${STOP_SCHEDULE:-QUIT/5/TERM/5/KILL/5}"

test -x $DAEMON || exit 0

start() {
    touch $LOGFILE && chown $DAEMONUSER $LOGFILE
    start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE \
        --background --chuid $DAEMONUSER --oknodo --exec $DAEMON -- $DAEMONOPTS
}

stop() {
    start-stop-daemon --stop --quiet --pidfile $PIDFILE --retry=$STOP_SCHEDULE \
        --oknodo
    rm -f $PIDFILE
}

status() {
    if [ -f $PIDFILE ]; then
        if kill -0 $(cat "$PIDFILE"); then
            echo "$NAME is running"
        else
            echo "$NAME process is dead, but pidfile exists"
        fi
    else
        echo "$NAME is not running"
    fi
}

case "$1" in
    start)
        echo "Starting $NAME"
        start
    ;;
    stop)
        echo "Stopping $NAME"
        stop
    ;;
    restart)
        echo "Restarting $NAME"
        stop
        start
    ;;
    status)
        status
    ;;
    *)
        echo "Usage: $0 {start|stop|restart|reload|status}"
        exit 2
    ;;
esac

exit 0
