#!/bin/sh
#	program:	cname
#	release:	1.5.0
#	input:		domain name on command line,
#			optional nameserver to direct queries to.
#	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).
#
# Copyright (C) 1993-2000 Paul A. Balyoz <pab@domtools.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
#

type=CNAME

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

if test $# -lt 1 -o $# -gt 2; then
	echo "usage: $0 [@nameserver] dom.ain." >&2
	echo 'ERROR'
	exit 1
fi

dom=
nameservers=
atnameserver=
while test $# -gt 0; do
	case "$1" in
		@*)  atnameserver="$1" nameservers=`echo $1 | sed -e 's/@//'` ;;
		*)  dom="$1" ;;
	esac
	shift
done
if test x"$dom" = x""; then
	echo "$0: No domain name specified; aborting." >&2
	echo "usage: $0 [@nameserver] dom.ain." >&2
	echo 'ERROR'
	exit 1
fi

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

zone=`/usr/local/domtools/bin/zone $atnameserver $dom`
if test $? -ne 0; then
	echo "$0: cannot determine the zone that $dom lives in." >&2
	echo 'ERROR'
	exit 1
fi

if test x"$nameservers" = x""; then
	nameservers=`/usr/local/domtools/bin/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
fi

for ns in $nameservers; do
	dig @$ns $dom $type +ret=2 +pfset=0x2024 | /usr/local/domtools/bin/digparse | /usr/local/bin/perl5.00502 -pe 'END{$? = !defined $l} s/^\S+\s+//; s/[\t ]+/ /g; $l++' > $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

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

rm -f $TMP
exit $status
