#!/bin/sh

COMMAND=$(basename $0 .sh)
WLDIR=/var/tmp/univnautes-sp-whitelists/

# lock to avoid concurrent updates
LOCK=/var/run/univnautes-sp-$COMMAND.lock
if [ -r $LOCK ]
then
	PID=`cat $LOCK`
	echo "$COMMAND locked by $LOCK"
	ps waux | grep "$PID" | grep $COMMAND | grep -vq grep && exit
	echo "... but PID $PID is not a $COMMAND, continue"
fi
unlock() {
	rm -f $LOCK
	exit
}
trap unlock INT TERM EXIT
echo $$ > $LOCK

## real start

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

rm -rf $WLDIR

cd /usr/local/univnautes/sp
./manage.py prepare-whitelists

cd $WLDIR
for wl in *
do
	. ${wl}/conf.sh
	log "download whitelist $CODENAME from $URL"
	if [ -r ${wl}/cacert.pem ]
	then
		CHECK="--ca-certificate=${WLDIR}/${wl}/cacert.pem"
	else
		CHECK="--no-check-certificate"
		log "warn: --no-check-certificate for whitelist $CODENAME"
	fi
	wget --quiet --tries=1 --timeout=10 $CHECK -O ${wl}/whitelist $URL
	RET=$?
	if [ $RET -ne 0 ]
	then
		rm -f ${wl}/whitelist
		log "warn: ERROR while downloading $URL"
	fi
done

# concat all whitelists
cat $WLDIR/*/whitelist | \
	grep -v "\(^[[:space:]]*#\)\|\(^[[:space:]]*$\)" | \
	tr -d '
' | \
	sed 's#\(^[^/]*$\)#\1/32#' | \
	sort -u > $WLDIR/all

# computes differences between the whitelist and the actual ipfw table
cd /usr/local/univnautes/sp
for ctx in $(./manage.py configxml get cpnames); do
        WL=/var/tmp/ipfw-table42-$ctx
        /sbin/ipfw -x $ctx table 42 list | cut -f1 -d" " | sort -u > $WL-actual
        cat $WLDIR/all $WL-actual | sort | uniq -d > $WL-common
        cat $WLDIR/all $WL-common | sort | uniq -u > $WL-add
        cat $WL-actual $WL-common | sort | uniq -u > $WL-delete
        for i in `cat $WL-add`
        do
                log "$ctx: add $i"
                /sbin/ipfw -x $ctx -q table 42 add $i
        done
        for i in `cat $WL-delete`
        do
                log "$ctx: delete $i"
                /sbin/ipfw -x $ctx -q table 42 delete $i
        done
done
