#!/bin/sh
### BEGIN INIT INFO
# Provides:          bastionguard-rootguard
# Required-Start:    $local_fs $remote_fs
# Required-Stop:     $local_fs $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: BastionGuard RootGuard security monitor
# Description:       Monitors anomalous root transitions and protected metadata.
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin
NAME=bastionguard-rootguard
DAEMON=/usr/libexec/bastionguard/bastionguard-rootguard
PIDFILE=/run/$NAME.pid
POLICY=/etc/bastionguard/rootguard.conf
DESC="BastionGuard RootGuard"
DAEMON_ARGS="--policy $POLICY"

[ -r /etc/default/$NAME ] && . /etc/default/$NAME

is_running() {
    [ -r "$PIDFILE" ] || return 1
    pid=$(cat "$PIDFILE" 2>/dev/null) || return 1
    kill -0 "$pid" 2>/dev/null
}

start_service() {
    if is_running; then
        echo "$DESC is already running."
        return 0
    fi
    install -d -m 0755 /run /var/log/bastionguard
    start-stop-daemon --start --quiet --background --make-pidfile \
        --pidfile "$PIDFILE" --exec "$DAEMON" -- $DAEMON_ARGS
}

stop_service() {
    start-stop-daemon --stop --quiet --retry=TERM/10/KILL/5 \
        --remove-pidfile --pidfile "$PIDFILE" --exec "$DAEMON" || true
}

case "${1:-}" in
    start)
        echo "Starting $DESC"
        start_service
        ;;
    stop)
        echo "Stopping $DESC"
        stop_service
        ;;
    restart|force-reload)
        stop_service
        start_service
        ;;
    reload)
        if is_running; then
            kill -HUP "$(cat "$PIDFILE")"
        else
            echo "$DESC is not running." >&2
            exit 3
        fi
        ;;
    status)
        if is_running; then
            echo "$DESC is running (PID $(cat "$PIDFILE"))."
            exit 0
        fi
        echo "$DESC is not running."
        exit 3
        ;;
    *)
        echo "Usage: $0 {start|stop|restart|reload|force-reload|status}" >&2
        exit 2
        ;;
esac
exit 0
