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

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

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

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

# Print just the right type of resource records without following CNAME records
sed -n -e "s/^$type //p" < $TMP

rm -f $TMP
exit $status
