#!/bin/sh

# config
. /usr/local/univnautes/etc/univnautes.conf

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

downloadwl() {
	FETCH=$WL.fetch.$$
	if [ ! -z "$WLURL" ]
	then
		if [ -r "$WLCA" ]
		then
			log "download whitelist from $WLURL (ca=$WLCA)"
			wget --quiet --timeout=300 --ca-certificate=$WLCA -O $FETCH $WLURL
			RET=$?
		else
			log "download whitelist from $WLURL (no-check-certificate)"
			wget --quiet --timeout=300 --no-check-certificate -O $FETCH $WLURL
			RET=$?
		fi
		if [ $RET -ne 0 ]
		then
			rm -f $FETCH
			log "ERROR while downloading $WLURL"
			exit 1
		fi
	else
		log "no whitelist url : only use static (if any)"
		echo "# no whitelist url" > $FETCH
	fi
	if [ -r "$WLSTATICIPS" ]
	then
		cat $FETCH $WLSTATICIPS > $WL.fetch
	else
		cat $FETCH > $WL.fetch
	fi
	rm -f $FETCH
}

reload() {
	downloadwl
	# computes differences between the whitelist and the actual ipfw table
	cp -af $WL.fetch $WL
	grep -v "\(^[[:space:]]*#\)\|\(^[[:space:]]*$\)" $WL | tr -d '
' | sed 's#\(^[^/]*$\)#\1/32#' | sort -u > $WL-wanted
	/sbin/ipfw table 42 list | cut -f1 -d" " | sort -u > $WL-actual
	cat $WL-wanted $WL-actual | sort | uniq -d > $WL-common
	cat $WL-wanted $WL-common | sort | uniq -u > $WL-add
	cat $WL-actual $WL-common | sort | uniq -u > $WL-delete
	for i in `cat $WL-add`
	do
		echo add $i | logger -p local4.info -t update-whitelist
		/sbin/ipfw -q table 42 add $i
	done
	for i in `cat $WL-delete`
	do
		echo delete $i | logger -p local4.info -t update-whitelist
		/sbin/ipfw -q table 42 delete $i
	done
}

resetwl() {
	log "resetting..."
	downloadwl
	cp -af $WL.fetch $WL
	/sbin/ipfw -fq table 42 flush
	for i in `grep -v "\(^[[:space:]]*#\)\|\(^[[:space:]]*$\)" $WL | tr -d '
' | sed 's#\(^[^/]*$\)#\1/32#'`
	do
		echo add $i | logger -p local4.info -t update-whitelist
		/sbin/ipfw -q table 42 add $i
	done
	log "whitelist reset done"
}

if [ x$1 = xreset ]
then
	resetwl
else
	# call by minicron (no arg)
	reload
fi

log `/sbin/ipfw table 42 list | wc -l`" entries in whitelist (ipfw table 42)"

