#!/bin/sh

. /etc/rc.common

daemonpath="/Library/StartupItems/BFilter"
daemonname="BFilterDaemon"
daemonpid="/var/run/${daemonname}.pid"
cachedir="/Library/Caches/net.sourceforge.bfilter"

StartService ()
{
	ConsoleMessage "Starting BFilter"
	if ! test -f "${cachedir}"; then
		mkdir "${cachedir}"
	fi
	chown nobody:nobody "${cachedir}"
	"${daemonpath}/${daemonname}" -u nobody -g nobody -p "${daemonpid}" \
	-C "${cachedir}"
}

StopService ()
{
	ConsoleMessage "Stopping BFilter"
	"${daemonpath}/${daemonname}" -k -p "${daemonpid}"
}

RestartService ()
{
	StopService;
	StartService;
}

# Reconfiguring does the following:
# 1. Checks if the listen port is available.
#   1.1) If it's not, another port is selected and config file is updated.
# 2. Updates network profiles (Locations).
ReconfigureService ()
{
	ConsoleMessage "Reconfiguring BFilter"
	"${daemonpath}/${daemonname}" -u nobody -g nobody -p "${daemonpid}" \
	--reconfigure
	# Note 1: Reconfiguring must be done with the same -u and -g as
	# normal operation.  Failure to do so may result in automatic
	# port selection not working.
	# Note 2: We supply -p to prevent reconfiguring while another instance
	# is running.
}

case "$1" in
  reconfigure) ReconfigureService;;
  *) RunService "$1";;
esac
