#!/bin/sh

. /usr/local/univnautes/etc/univnautes.conf
UPDATER=/usr/local/bin/univnautes-update-whitelist.sh

log() {
	logger -p local4.info -t whitelist -- "$*"
}

start() {
	log "start"
	# load ipfw.ko if it's not here
	/sbin/kldstat | grep -q ipfw.ko || /sbin/kldload ipfw.ko
	# if table 42 is not activated (it allows traffic to IdPs)
	# NOTE : normally, these rules are already created by /etc/inc/captiveportal.inc
	if ! /sbin/ipfw list 65500 > /dev/null 2>&1
	then
		/sbin/ipfw -fq add 65500 allow ip from any to "table(42)" in
		/sbin/ipfw -fq add 65501 allow ip from "table(42)" to any out
		/sbin/ipfw -fq table 42 flush
	fi
	rm -f $WL $WL.fetch
	$UPDATER reset
	_cronstart
}

stop() {
	_cronstop
	/sbin/ipfw -q table 42 flush
	log "stopped"
}

_cronstart() {
	_cronstop
	/usr/local/bin/minicron $REFRESH /var/run/update-whitelist-cron.pid $UPDATER
	log "update-whitelist cron started"
}

_cronstop() {
	if [ -r /var/run/update-whitelist-cron.pid ]
	then
		PID=`cat /var/run/update-whitelist-cron.pid`
		ps waux | grep "$PID" | grep minicron | grep -vq grep && kill $PID
		rm -f /var/run/update-whitelist-cron.pid
		log "update-whitelist cron stopped"
	fi
}

$1

