#!BOURNESHELL
#	program:	mx
#	input:		domain name on command line.
#	output:		one or more MX 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=MX

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"
	zone=`DOMBIN/zone $dom`
	if test $? -ne 0; then
		echo "$0: cannot determine the zone that $dom lives in." >&2
		echo 'ERROR'
		exit 1
	fi

	nameservers=`DOMBIN/ns $zone`
	if test $? -ne 0 -o x"$nameservers" = x""; then
		echo "$0: cannot find any nameservers for zone $zone" >&2
		echo 'ERROR'
		exit 1
	fi

	for ns in $nameservers; do
		dig @$ns $dom $type | 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: 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
