#!/bin/bash
# (C) 2006 Mark Boddington, http://www.badpenguin.co.uk
# Licensed under the GNU GPL Version 2.

# Space separated list of hostnames to allow
myHosts="somehost.dyndns.com someotherhost.dyndns.com"

# Space separated list of ports to allow
myPorts="22 80"

PATH=/usr/sbin:/usr/bin:/sbin:/bin

DIG="dig +short"
cache=/var/cache/ddns
newca=/var/cache/ddns.current
log=/var/log/ddnshole.log
chain=DDNS

# Flush the chain and add the return
cat > $newca <<-EOF
	iptables -F $chain 
	iptables -A $chain -j RETURN
EOF

# Our host will always have some IP so check that we're not running with an empty ruleset
lines=$( iptables -L $chain | wc -l )
if [ $lines -eq 3 ]
then
   # There are no entries in the chain, copy the newca over cache.
   cp $newca $cache
fi


# for each host add some rules
for host in $myHosts
do
	addr=$( $DIG $host | tail -n 1 )
	if [  "$(echo $addr | sed -e 's/[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*/success/g')" == "success" ]
	then
		for port in $myPorts
		do
			echo "iptables -I $chain -s $addr -p tcp --dport $port -j ACCEPT # $host " >> $newca
		done
	else
		date +"DNS Check Failed: %Y%m%d %H:%M" >> $log
		echo "No dns info for $host? addr = \"$addr\"" >> $log
		echo "No updates this time" >> $log
		echo >> $log
	fi
done

if [ -f $cache ]
then
   differ=$( diff --brief $cache $newca )
else
   differ=yes
fi

if [ -n "$differ" ]
then
	date +"Changed IP: %Y%m%d %H:%M" >> $log
	grep "#" $newca >> $log
	echo >> $log
	cp $newca $cache
	cat $cache | bash
fi


