#!BOURNESHELL
#	program:	ns
#	input:		zone domain name on command line.
#	output:		one or more NS resource records listed one per line,
#			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=NS

TMP="/tmp/`basename $0`.$$"
TMPRR="${TMP}rr"
TMPCNAME="${TMP}cname"

if test $# -ne 1; then
	echo "usage: $0 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

repeatflag=true
while $repeatflag; do
        repeatflag=false
        dom="$1"

	dig $dom $type | awk -f $AWK > $TMP
	status=$?
	if test $status -ne 0; then
		echo "$0: no $type resource records found for $dom" >&2
		echo 'ERROR'
		rm -f $TMP
		exit 1
	fi

        # If regular records found, print them; otherwise if CNAME found,
        # follow it recursively (unless infinite loop detected).
        perl -ne "if (/^CNAME /) {print STDERR;last;} else {print if s/^$type //;}" < $TMP > $TMPRR 2> $TMPCNAME
        if test -s $TMPRR; then
                cat $TMPRR
        elif test -s $TMPCNAME; then
                set `awk '{print $2}' < $TMPCNAME`              # get ready to try again
		if isequal x"$1" x"$dom" >/dev/null 2>&1; then	# infinite CNAME loop sensing!
                        echo "$0: infinite CNAME loop detected for $dom" >&2
                        echo 'ERROR'
                        rm -f $TMP $TMPRR $TMPCNAME
                        exit 100
                else
                        repeatflag=true
                        rm -f $TMPRR $TMPCNAME
                fi
        fi
done

rm -f $TMP $TMPRR $TMPCNAME
exit $status
