#!/bin/sh
# DSM service control for SvrGuard.
#
# DSM calls this with start | stop | status | log. Everything the package
# writes lives under .../var, which DSM preserves across upgrades — the
# database and the enrolment key must survive a package update, or every
# upgrade would look like a new host to the hub and burn a seat.

PKG_DIR="/var/packages/SvrGuard/target"
VAR_DIR="/var/packages/SvrGuard/var"
BIN="${PKG_DIR}/bin/svrguard"
CFG="${VAR_DIR}/svrguard.ini"
PID="${VAR_DIR}/svrguard.pid"
LOG="${VAR_DIR}/svrguard.log"

running() {
    [ -f "$PID" ] || return 1
    pid=$(cat "$PID" 2>/dev/null)
    [ -n "$pid" ] || return 1
    # Confirm the pid is actually ours: a recycled pid belonging to some
    # other process must not be reported as "running", nor killed on stop.
    [ -d "/proc/$pid" ] || return 1
    grep -q svrguard "/proc/$pid/cmdline" 2>/dev/null || return 1
    return 0
}

case "$1" in
    start)
        if running; then
            echo "SvrGuard is already running"
            exit 0
        fi
        [ -x "$BIN" ] || { echo "binary missing: $BIN"; exit 1; }
        [ -f "$CFG" ] || { echo "config missing: $CFG"; exit 1; }
        "$BIN" run -config "$CFG" >> "$LOG" 2>&1 &
        echo $! > "$PID"
        sleep 1
        running || { echo "SvrGuard failed to start; see $LOG"; exit 1; }
        exit 0
        ;;
    stop)
        if running; then
            pid=$(cat "$PID")
            kill "$pid" 2>/dev/null
            # Give the pass in flight a chance to commit its transaction
            # before escalating; a half-written SQLite write is worse than
            # a slow shutdown.
            i=0
            while [ $i -lt 15 ] && running; do sleep 1; i=$((i+1)); done
            running && kill -9 "$pid" 2>/dev/null
        fi
        rm -f "$PID"
        exit 0
        ;;
    status)
        if running; then
            echo "SvrGuard is running"
            exit 0
        fi
        echo "SvrGuard is not running"
        exit 3   # DSM reads 3 as "stopped"
        ;;
    log)
        echo "$LOG"
        exit 0
        ;;
    *)
        echo "usage: $0 {start|stop|status|log}"
        exit 1
        ;;
esac
