#!/bin/sh

#set -x # print all commands for debugging.

HOST="w4.objektdata.se"
RET=0

function dbg {
	echo $1
}

function errorx {
	echo -ne '\E[31;4m' # red
	echo -ne "\033[1m" >&2 # bold
	echo "!!!!! " $1 >&2
	echo -ne "\033[0m" >&2 #unbold
	tput sgr0 # reset terminal (no colors)
}

if [ "$1" != "" ]; then
	HOST=$1
fi

set -u # treat unset variables as errors.

dbg "Checking target host $HOST"

DOMAIN=$(echo $HOST | cut -d. -f2-)
dbg "DNS servers for $DOMAIN:"



LASTSERIAL=""
LASTHOST=""

for NS in $(host -t ns $DOMAIN | cut -d' ' -f4)
do
	dbg "+ $NS"
	SERIAL=$(host -t soa $DOMAIN $NS | grep SOA | cut -d' ' -f7)
	dbg "SOA Serial:$SERIAL"

	if [ "$LASTSERIAL" = "" ]; then
		LASTSERIAL=$SERIAL
	fi

	if [ "$SERIAL" != "$LASTSERIAL" ]; then
		errorx "Zone serials out of sync: $SERIAL vs $LASTSERIAL (ns:$NS)"
		let RET++
	fi

	HOSTRESULT=$(host $HOST $NS | grep " has address ")
	dbg "$HOSTRESULT"

	if [ "$LASTHOST" = "" ]; then
		LASTHOST="$HOSTRESULT"
	fi

	if [ "$LASTHOST" != "$HOSTRESULT" ]; then
		errorx "Host out of sync: $HOSTRESULT (ns:$NS)"
		let RET++
	fi

done

exit $RET
