#!/bin/sh

doit=1

# files we need
list=
running="/tmp/.running.firewall.rules"
tmp1="/tmp/.${0}.1.$$.${RANDOM}"
tmp2="/tmp/.${0}.2.$$.${RANDOM}"

# get the arguments
while [ ! -z "${1}" ]
do
	case "${1}" in
		'-p')	doit=0
			;;
			
		'-f')	rm -f "${running}"
			;;
			
		*)	list="${1}"
			break
			;;
	esac
	
	shift
done

# make sure we have a list
if [ -z "${list}" -o ! -f "${list}" ]
then
	echo >&2 "USAGE: $0 [-p|-f] filename"
	echo >&2 "Use -p for pretend (don't touch the firewall, just show me)."
	echo >&2 "Use -f for fresh (don't diff, just apply all the list again)."
	exit 1
fi

# make sure a running list file exists
test ! -f "${running}" && touch "${running}"

# sort the two files
sort -u "${running}" >"${tmp1}"
sort -u "${list}" >"${tmp2}"

# find their differences
diff -u "${tmp1}" "${tmp2}"	|\
	grep ^[\+\-][0-9]	|\
	sed "s/\+/\+ /"		|\
	sed "s/\-/\- /"		|\
while read what ip name
do
	case $what in
		'+')
			echo >&2 "Adding IP '${ip}' in interface '${name}'"
			if [ ${doit} -eq 1 ]
			then
				/sbin/iptables -t filter -A INPUT -i eth0 -s $ip -j in_$name
				/sbin/iptables -t filter -A INPUT -o eth0 -d $ip -j out_$name
			fi
			;;
			
		'-')
			echo >&2 "Removing IP '${ip}' from interface '${name}'"
			if [ ${doit} -eq 1 ]
			then
				/sbin/iptables -t filter -D INPUT -i eth0 -s $ip -j in_$name
				/sbin/iptables -t filter -D INPUT -o eth0 -d $ip -j out_$name
			fi
			;;
			
		*)
			echo "Cannot understand '$what'."
			;;
	esac
done

rm -f "${tmp1}"
rm -f "${tmp2}"

test ${doit} -eq 1 && cp -f "${list}" "${running}"

exit 0
