#!/bin/sh

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

DNSSERVER="<%= dns_nsupdate_server -%>"
DNSZONE="<% if has_variable?("dns_nsupdate_zone") -%><%= dns_nsupdate_zone -%><% end %>"
MYNAME="<%= dns_nsupdate_name -%>"
MYKEY="<%= dns_nsupdate_key -%>"

# if zone is not defined take it from fqdn
if [ "${DNSZONE}" = "" ]; then
    DNSZONE=`echo ${MYNAME} | cut -d . -f 2-`
fi


# determine our current address
case `uname` in
    Linux)
	MYIF="`route -n | awk '/^0.0.0.0/ { print $8 }'`"
	MYADDR="`ifconfig ${MYIF} | sed -n '/inet/s/.*addr:\([0-9.]*\).*/\1/p'`"
	;;
    OpenBSD)
	MYADDR="`route -n get default | awk '/if address/ { print $3 }'`"
	;;
esac


# try to get current addr/name from dns
CURADDR=`dig +short @${DNSSERVER} ${MYNAME} A 2>/dev/null`
if [ $? -ne 0 ]; then
    # we should get this only in dns errors so exit quietly
    exit 1
fi


# exit now if we are up to date
if [ "${CURADDR}" = "${MYADDR}" ]; then
    exit 0
fi


# update record
nsupdate -v <<EOF
server ${DNSSERVER}
zone ${DNSZONE}
key ${MYKEY}
update delete ${MYNAME}
update add ${MYNAME} 60 A ${MYADDR}
show
send
EOF
