#!/bin/sh

# PROVIDE: tis_agent
# REQUIRE: LOGIN ipfw
# KEYWORD: shutdown
#
# Add to /etc/rc.conf (or use sysrc):
#
# tis_agent_enable="YES"
# tis_agent_config="/usr/local/etc/tis-agent.json"  (default)
# tis_agent_flags=""                                 (extra global flags)
#
# Everything else - the token, targets, jobs and hits - is in the
# configuration file (mode 600, it holds the token). "service tis_agent
# reload" re-reads it; start and reload check it first.
#
# Output goes to syslog, without the program's own timestamps:
# tis_agent_syslog_facility   Default: security (/var/log/security)
# tis_agent_syslog_priority   Default: notice

# rc.subr reads these variables and calls the functions:
# shellcheck disable=SC1091,SC2034,SC2154

. /etc/rc.subr

name="tis_agent"
rcvar="${name}_enable"

load_rc_config ${name}

: "${tis_agent_enable:="NO"}"
: "${tis_agent_user:="root"}"
: "${tis_agent_config:="/usr/local/etc/tis-agent.json"}"
: "${tis_agent_syslog_facility:="security"}"
: "${tis_agent_syslog_priority:="notice"}"

command="/usr/local/bin/tis-agent"
pidfile="/var/run/${name}.pid"
sig_reload="HUP"
extra_commands="reload"

start_precmd="${name}_prestart"
start_cmd="${name}_start"
reload_precmd="${name}_check"

tis_agent_check() {
    "${command}" -config "${tis_agent_config}" check >/dev/null
}

tis_agent_prestart() {
    tis_agent_check || return 1
    # Hit counting reads packets from a divert socket; without the module
    # only the hit counting fails, the jobs run.
    if ! kldstat -q -m ipdivert; then
        kldload ipdivert || echo "Warning: cannot load ipdivert; hits will not be counted." >&2
    fi
}

tis_agent_start() {
    if [ -n "${rc_pid}" ]; then
        echo "${name} already running? (pid=${rc_pid})."
        return 1
    fi

    echo "Starting ${name}."
    # -p: the pid of tis-agent itself, which rc.subr checks, stops and
    # sends SIGHUP to. tis_agent_flags unquoted: it holds several flags.
    # shellcheck disable=SC2086
    /usr/sbin/daemon -f -S -l "${tis_agent_syslog_facility}" -s "${tis_agent_syslog_priority}" \
        -T "${name}" -P "/var/run/${name}_daemon.pid" -p "${pidfile}" \
        -u "${tis_agent_user}" "${command}" -log-timestamps=false -config "${tis_agent_config}" \
        ${tis_agent_flags} daemon
}

run_rc_command "$1"
