#!/bin/sh
# Control the agent service through systemd (native sigma_agent.service) when
# the host runs systemd, launchd on macOS, else the SysV init script. One place
# so the postinst, %post, and sigma-agent-setup all do the right thing everywhere.
#   Usage: sigma-agent-svc <start|stop|restart|enable|status>
a="${1:-restart}"
LD=/Library/LaunchDaemons/com.sigmasrc.agent.plist
if [ "`uname`" = Darwin ] && [ -f "$LD" ]; then
    # Never fall through to the init script here: it would start a second
    # scheduler outside launchd.
    case "$a" in
        enable)  launchctl print system/com.sigmasrc.agent >/dev/null 2>&1 \
                     || launchctl bootstrap system "$LD" ;;
        # Not loaded (e.g. after stop): bootstrap starts it (RunAtLoad) --
        # no kickstart -k then, which would kill the fresh scheduler at once.
        start|restart)
                 if ! launchctl print system/com.sigmasrc.agent >/dev/null 2>&1; then
                     launchctl bootstrap system "$LD"
                 elif [ "$a" = restart ]; then
                     launchctl kickstart -k system/com.sigmasrc.agent
                 else
                     launchctl kickstart system/com.sigmasrc.agent   # no-op if running
                 fi ;;
        # bootout, not 'kill TERM': it stops the job for good (until start or
        # reboot) whatever the exit status -- an agent without the SIGTERM
        # handler died "by signal", which KeepAlive restarted 10 s later.
        stop)    if launchctl print system/com.sigmasrc.agent >/dev/null 2>&1; then
                     launchctl bootout system/com.sigmasrc.agent
                 fi ;;
        # -E: BSD sed has no \| in basic regular expressions
        status)  launchctl print system/com.sigmasrc.agent 2>/dev/null \
                     | sed -n -E 's/^[[:space:]]*(state|pid|last exit code) = /\1: /p' \
                     | grep . || echo "state: not loaded (stopped)" ;;
        *)       echo "usage: $0 <start|stop|restart|enable|status>" >&2; exit 2 ;;
    esac
elif [ -d /run/systemd/system ] && command -v systemctl >/dev/null 2>&1; then
    case "$a" in
        enable) systemctl enable sigma_agent >/dev/null 2>&1 || true ;;
        *)      systemctl "$a" sigma_agent ;;
    esac
elif [ -x /etc/init.d/sigma_agent ]; then
    case "$a" in
        enable) : ;;   # handled by update-rc.d/chkconfig at install time
        *)      /etc/init.d/sigma_agent "$a" ;;
    esac
fi
