#!BOURNESHELL
#	program:	soalist
#	input:		zone domain name on command line.
#	output:		a list of all authoritative nameservers for the zone with
#			their respective SOA records,
#			or the word "ERROR" (distinguishable from a real
#			record because it has no period on the end).
#	exit value:	0 if succeeds, 1 if fails (and "ERROR" output).

AWK=DOMLIB/digoutany.awk
type=SOA

TMP="/tmp/`basename $0`.$$"

if test $# -ne 1; then
	echo "usage: $0 zone.dom.ain." >&2
	echo 'ERROR'
	exit 1
fi

if test "`DOMBIN/type $1`" = "forward"; then
	echo "$0: argument $1 is not a domain name." >&2
	echo 'ERROR'
	exit 1
fi

domain="$1"

# If they slipped us the root domain, there's no parent zone above it,
# so we just query all the root domain nameservers instead.

if test x"$domain" = x"."; then
	zone="."
	parentdomain="."
	parentzone="."
	parentnameservers=`DOMBIN/root`
	if test $? -ne 0 -o x"$parentnameservers" = x""; then
		echo "$0: cannot find the names of nameservers for the root domain." >&2
		echo 'ERROR'
		exit 1
	fi
else

# Find what zone the given domain is in (it should be it's own zone!)

	zone=`DOMBIN/zone $domain`
	if test $? -ne 0; then
		echo "$0: cannot find the zone of the domain $domain" >&2
		echo 'ERROR'
		exit 1
	fi
	if DOMBIN/isequal "$zone" "$domain" > /dev/null; then
		:
	else
		echo "$0: $domain is not truly a zone, perhaps you should use $zone" >&2
		echo 'ERROR'
		exit 1
	fi

# Its a regular zone; find the parent zone 

	parentdomain=`DOMBIN/basedomain $zone`
	parentzone=`DOMBIN/zone $parentdomain`
	if test $? -ne 0; then
		echo "$0: cannot find the zone of the parent domain $parentdomain" >&2
		echo 'ERROR'
		exit 1
	fi

	parentnameservers=`DOMBIN/ns $parentzone`
	if test $? -ne 0 -o x"$parentnameservers" = x""; then
		echo "$0: cannot find the names of the nameservers for parent domain $parentdomain" >&2
		echo 'ERROR'
		exit 1
	fi
fi

# Find a parent zone nameserver that will tell us which nameservers are supposed to be
# authoritative for the zone we were given.

for pns in $parentnameservers; do
	dig @$pns $zone NS | awk -f $AWK > $TMP
	status=$?
	if test $status -eq 0 -o $status -eq 3; then
		break
	fi
done
if test $status -ne 0; then
	echo "$0: could not determine nameservers for $domain from any $parentdomain name server." >&2
	echo 'ERROR'
	rm -f $TMP
	exit 1
fi
nameservers=`sed -n -e 's/^NS //p' < $TMP`
rm -f $TMP

# Now query every name server for our zone, displaying their SOA records.
# I added the "head -1" because some zones return 2 SOA records for some reason (strange).
for ns in $nameservers; do
	rr=`dig @$ns $zone $type | awk -f $AWK | head -1`
	echo "$ns $rr" | perl -ne '($ns,$rr)=split (/[ \t]+/,$_,2); printf "%-20s -> %s",$ns,$rr;'
done

rm -f $TMP
exit 0
