#!/bin/sh

# PROVIDE: hostwatch
# REQUIRE: DAEMON
# BEFORE: LOGIN
# KEYWORD: shutdown

# Add the following lines to /etc/rc.conf to enable hostwatch discovery service:
# hostwatch_enable (bool):         Set to YES to enable hostwatch
#                                  Default: NO
# hostwatch_pidfile (str):         Pidfile to store pid of hostwatch process
#                                  Default: /var/run/hostwatch.pid
# hostwatch_skip_nets:             list of networks to ignore
#                                  Default: ""
# hostwatch_flags (str):           extra flags passed to hostwatch
#                                  Default: "-c -S"
# hostwatch_database (str):        location of the database (directory)
#                                  Default: "/var/db/hostwatch"
# hostwatch_interfaces (str):      interfaces to bind to, all when not set
#                                  Default: ""

. /etc/rc.subr

name="hostwatch"
rcvar=hostwatch_enable

load_rc_config ${name}

hostwatch_enable=${hostwatch_enable:-"NO"}
hostwatch_pidfile=${hostwatch_pidfile:-"/var/run/hostwatch.pid"}
hostwatch_flags=${hostwatch_flags:-"-c -S"}
hostwatch_database=${hostwatch_database:-"/var/db/hostwatch"}

# do not accept these as user input
command="/usr/local/bin/hostwatch"
start_precmd="hostwatch_prestart"
pidfile=${hostwatch_pidfile}
hostwatch_chuser="hostd"
hostwatch_chgroup="hostd"

hostwatch_flags="${hostwatch_flags} -P ${hostwatch_pidfile}"
hostwatch_flags="${hostwatch_flags} -d ${hostwatch_database}/hosts.db"

[ -n "${hostwatch_chuser}" ] && hostwatch_flags="${hostwatch_flags} -u ${hostwatch_chuser}"
[ -n "${hostwatch_chgroup}" ] && hostwatch_flags="${hostwatch_flags} -g ${hostwatch_chgroup}"

for net in ${hostwatch_skip_nets}; do
    hostwatch_flags="${hostwatch_flags} -s ${net}"
done

for ifn in ${hostwatch_interfaces}; do
    hostwatch_flags="${hostwatch_flags} -i ${ifn}"
done

hostwatch_prestart()
{
    if ! run_rc_command status > /dev/null; then
        rm -f "${hostwatch_pidfile}"
    fi
    mkdir -p ${hostwatch_database}
    touch ${hostwatch_database}/hosts.db
    if [ -n "${hostwatch_chuser}" ]; then
        chown -R ${hostwatch_chuser} ${hostwatch_database}
    fi
    if [ -n "${hostwatch_chgroup}" ]; then
        chown -R :${hostwatch_chgroup} ${hostwatch_database}
    fi
}

run_rc_command "${1}"
