#!/bin/sh
# @(#) $Id: arpwatch.sh.in 1514 2019-12-17 00:44:37Z leres $ (LBL)
#
# PROVIDE: arpwatch
# REQUIRE: NETWORKING
# KEYWORD: shutdown
#

. /etc/rc.subr

name=arpwatch
rcvar=arpwatch_enable
load_rc_config ${name}
command=/usr/local/sbin/${name}
required_dirs=${arpwatch_dir}
arpwatch_enable=${arpwatch_enable:-"NO"}
arpwatch_dir=${arpwatch_dir:-"/usr/local/arpwatch"}
restart_cmd=${name}_restart_cmd

prep_datfile()
{
	fn=$1
	if [ ! -e ${fn} ]; then
		if [ -e ${fn}- ]; then
			cp ${fn}- ${fn}
		else
			touch ${fn}
		fi
	fi
}

arpwatch_precmd()
{
	cmd=$1
	interface=$2

	if [ -n "${interface}" ]; then
		# Named interface
		fn=${arpwatch_dir}/arp.${interface}.dat
		pidfile=/var/run/arpwatch-${interface}.pid
	else
		# Default interface
		fn=${arpwatch_dir}/arp.dat
		pidfile=/var/run/arpwatch.pid
	fi

	if [ $cmd == start ]; then
		prep_datfile ${fn}
	fi
	ltr ${interface} . _ _interface
	eval options=\$arpwatch_${_interface}_options
	command_args="-i ${interface} -f ${fn} -P ${pidfile} ${options}"
}

arpwatch_restart_cmd()
{
	if [ -n "${arpwatch_interfaces}" ]; then
		# One or more named interface
		for interface in ${arpwatch_interfaces}; do
			arpwatch_precmd stop ${interface}
			run_rc_command stop
		done
		for interface in ${arpwatch_interfaces}; do
			arpwatch_precmd start ${interface}
			run_rc_command start
		done
	else
		# Default interface
		arpwatch_precmd stop
		run_rc_command stop
		arpwatch_precmd start
		run_rc_command start
	fi
}

if [ "$1" = restart ]; then
	arpwatch_precmd $1
	run_rc_command $1
elif [ -n "${arpwatch_interfaces}" ]; then
	# One or more named interface
	for interface in ${arpwatch_interfaces}; do
		arpwatch_precmd $1 ${interface}
		run_rc_command $1
	done
else
	# Default interface
	arpwatch_precmd $1
	run_rc_command $1
fi
