#!/bin/sh
#
# PROVIDE: netflector
# REQUIRE: LOGIN
# KEYWORD: shutdown
#
# Add the following to /etc/rc.conf to enable netflector:
#
#   netflector_enable="YES"
#
# Optional:
#
#   netflector_config="/path/to/netflector.toml"   # default /usr/local/etc/netflector.toml
#   netflector_flags="-r"                          # options for daemon(8), e.g. restart on exit
#   netflector_carp_vhid="1"                       # only start if this CARP vhid is MASTER
#   netflector_carp_interface="em0"                # interface holding it; needed if the vhid is reused
#   netflector_log_target="syslog"                 # the default; empty leaves it to the config file
#   netflector_user="netflector"                   # the default; empty leaves it to the config file

. /etc/rc.subr

name="netflector"
rcvar="netflector_enable"
desc="Reflect link-local service discovery between interfaces"

load_rc_config $name

: ${netflector_enable:="NO"}
: ${netflector_config:="/usr/local/etc/netflector.toml"}
: ${netflector_carp_vhid:=""}
: ${netflector_carp_interface:=""}
: ${netflector_log_target="syslog"}
: ${netflector_user="netflector"}

if [ -n "${netflector_log_target}" ]; then
    netflector_env="${netflector_env:+${netflector_env} }NETFLECTOR_LOG_TARGET=${netflector_log_target}"
fi

if [ -n "${netflector_user}" ]; then
    netflector_env="${netflector_env:+${netflector_env} }NETFLECTOR_USER=${netflector_user}"
fi
# rc.subr would run daemon(8) itself as ${name}_user through su(1), and the capture needs root.
netflector_user=""

# The pidfile must hold daemon(8) itself (-P), not the child: stop then terminates the supervisor,
# which forwards the signal and exits. Killing only the child would let a restarting supervisor
# (netflector_flags="-r") respawn it behind rc's back. The child's pid stays visible beside it.
pidfile="/var/run/${name}.pid"
child_pidfile="/var/run/${name}_child.pid"
netflector_bin="/usr/local/bin/${name}"

# daemon(8) backgrounds netflector. -S sends its stderr to syslog: the log when it stays on stderr,
# otherwise a panic or a startup error. -f lets go of the caller's stdout.
command="/usr/sbin/daemon"
command_args="-f -S -T ${name} -P ${pidfile} -p ${child_pidfile} ${netflector_bin} '${netflector_config}'"

start_precmd="${name}_precmd"
extra_commands="report"
report_cmd="${name}_report"

netflector_precmd()
{
    if [ ! -f "${netflector_config}" ]; then
        netflector_log err "${netflector_config} does not exist"
        exit 1
    fi

    # Refuse to start on a configuration the daemon would reject, so the failure is one clear message
    # here rather than a service that appears to start and is gone a moment later. --check-config parses
    # and validates only: it opens no interface and needs no privileges.
    if ! env ${netflector_env} ${netflector_bin} --check-config "${netflector_config}" > /dev/null 2>&1; then
        env ${netflector_env} ${netflector_bin} --check-config "${netflector_config}" 2>&1 | while read -r line; do
            netflector_log err "${line}"
        done
        netflector_log err "refusing to start: ${netflector_config} is not valid"
        exit 1
    fi

    # Checked after the config, not before: on a backup node a bad configuration should still be
    # reported now, rather than at failover.
    if [ -n "${netflector_carp_vhid}" ]; then
        state=$(carp_state "${netflector_carp_vhid}" "${netflector_carp_interface}")
        case "${state}" in
        MASTER)
            ;;
        "")
            netflector_log err "no CARP vhid ${netflector_carp_vhid} here; refusing to start"
            exit 1
            ;;
        *)
            netflector_log notice "CARP vhid ${netflector_carp_vhid} is ${state} here; not starting netflector"
            # A backup idling is no failure: exit, not return, so the start ends with status 0 and
            # forcestart cannot start a second active node.
            exit 0
            ;;
        esac
    fi
}

netflector_log()
{
    logger -t "${name}" -p "daemon.$1" "$2"
    printf '%s: %s\n' "$0" "$2" >&2
}

# A carp line reads "carp: MASTER vhid 1 advbase 1 advskew 0". Neither field identifies a group on its
# own: one interface can carry several vhids, and the same vhid can run on several interfaces as
# unrelated groups. $2 narrows ifconfig to the one that matters, and can be empty for a unique vhid.
# Prints the group's state, or nothing when no group has that vhid.
carp_state()
{
    ifconfig ${2:+"$2"} 2>/dev/null |
        awk -v vhid="$1" '$1 == "carp:" && $4 == vhid { print $2; exit }'
}

# SIGUSR1 must reach netflector itself: ${pidfile} holds daemon(8), which has no handler for it and
# would die, orphaning the daemon it supervises.
netflector_report()
{
    pid=$(check_pidfile "$child_pidfile" "$netflector_bin")
    if [ -z "$pid" ]; then
        err 1 "${name} is not running"
    fi
    kill -USR1 "$pid"
}

run_rc_command "$1"
