#! /bin/bash

# Version 20050618

# Updates the A and AAAA records for a domain name.

# Requires the following packages (on a Debian 3.1 system)
#
# GET:      libwww-perl
# ip:       iproute
# dig:      dnsutils
# nsupdate: dnsutils

set -eu

# start configuration

ZONE=robots.org.uk
KEY="$HOME/Work/Kxerces.robots.org.uk.+157+40913.key"

# end configuration

function ip_is_public {
	case $IP in
	10.* | 192.168.* | 169.254.*) #TODO: 172.16.0.0/12, others?
		return 1
		;;
	*)
		return 0
	esac
}

function print_transaction {
	local domain_name=$(hostname).$ZONE

	echo prereq yxdomain $domain_name
	echo update delete $domain_name

	for IP6 in $(ip -o -6 addr show scope global | awk '{print $4}')
	do
		echo "update add $domain_name 60 AAAA ${IP6%/*}"
	done
	
	local IP_public=no
	for IP in $(ip -o -4 addr show scope global | awk '{print $4}')
	do
		if ip_is_public $IP
		then
			IP_public=yes
			echo "update add $domain_name 60 A ${IP%/*}"
		fi
	done

	test $IP_public = no && echo "update add $domain_name 60 A $(GET http://robots.org.uk/ip.php)" #>> $file

	echo 'send'
}

print_transaction | tee >(nsupdate -k "$KEY")
