#!/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" ;;
        start|restart)
                 launchctl print system/com.sigmasrc.agent >/dev/null 2>&1 \
                     || launchctl bootstrap system "$LD"
                 launchctl kickstart -k system/com.sigmasrc.agent ;;
        stop)    launchctl kill TERM system/com.sigmasrc.agent ;;   # clean exit: KeepAlive does not restart it
        status)  launchctl print system/com.sigmasrc.agent | sed -n 's/^[[:space:]]*\(state\|pid\|last exit code\) = /\1: /p' ;;
        *)       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
