#!/bin/sh
#!/sbin/openrc-run
# For openRC on Gentoo delete the #!/bin/sh line so that it is run by openrc-run

### BEGIN INIT INFO
# Provides:          littlesnitch
# Required-Start:
# Required-Stop:
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# X-Start-Before:    networking
# Short-Description: Little Snitch network monitor daemon
### END INIT INFO

DAEMON=/usr/bin/littlesnitch
DAEMON_ARGS="--daemon --use-cap-sys-admin"
NAME=littlesnitch
PIDFILE=/run/${NAME}.pid

# Make sure the standard paths are in PATH, regardless of caller's environment
# but give the original $PATH precedence.
PATH="$PATH:/bin:/usr/bin:/sbin:/usr/sbin"
export PATH

# ##################
# OpenRC interface
# ##################
# Never used by SysVinit (unused functions in shell script)

description="Little Snitch network monitor daemon"

depend() {
    before net
}

start() {
    ebegin "Starting ${NAME}"
    start-stop-daemon --start --background \
        --make-pidfile --pidfile "${PIDFILE}" \
        --exec "${DAEMON}" -- ${DAEMON_ARGS}
    eend $?
}

stop() {
    ebegin "Stopping ${NAME}"
    start-stop-daemon --stop --pidfile "${PIDFILE}"
    eend $?
}

# ####################
# SysVinit interface
# ####################
# OpenRC passes the script name as "$1" and therefore takes the "*)" case.
# Make sure that code path is harmless.

case "$1" in
    start)
        start-stop-daemon --start --background \
            --make-pidfile --pidfile "${PIDFILE}" \
            --exec "${DAEMON}" -- ${DAEMON_ARGS}
        ;;
    stop)
        start-stop-daemon --stop --pidfile "${PIDFILE}"
        ;;
    restart)
        $0 stop
        $0 start
        ;;
    status)
        if [ -f "${PIDFILE}" ] && kill -0 "$(cat "${PIDFILE}")" 2>/dev/null; then
            echo "${NAME} is running"
        else
            echo "${NAME} is not running"
            exit 1
        fi
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|status}"
        # We must not exit here, openRC sources this file and takes this path
        ;;
esac
