#!BOURNESHELL
#	program:	subzone
#	purpose:	Print a list of sub-zones within this zone.
#			This is not recursive unless the "-r" flag is given.
#	input:		Domain name of a DNS zone on command line.
#	output:		A list of domain names of subzones within the given zone
#			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).
#
TMP=/tmp/subzone1.$$
TMP2=/tmp/subzone2.$$

SUBZONEAWK=DOMLIB/subzone.awk

usage() {
	echo "usage: $0 [-r] dom.ain." >&2
	echo 'ERROR'
	exit 1
}

if test $# -lt 1 -o $# -gt 2; then
	usage
fi

zone="" RECURSIVE=false
for arg do
	case "$arg" in
		-r)	RECURSIVE=true; shift ;;
		*)	if test x"$zone" = x""; then
				zone="$arg"
			else
				usage
			fi ;;
	esac
done
if test x"$zone" = x""; then 
        usage
fi

# Check if we were really given a zone or not.

realzone=`DOMBIN/zone $zone`
if test $? -ne 0 -o x"$realzone" = x"ERROR" -o x"$zone" != x"$realzone"; then
	echo "$0: the domain you gave me ($zone) is not a zone." >&2
	echo 'ERROR'
	exit 1
fi

# If we are going recursively, then print the current zone's name.

if $RECURSIVE; then
	echo $zone
fi

# Get the zone dump for this zone.

DOMBIN/axfr $zone > $TMP
if test $? -ne 0; then
	echo "$0: cannot get zone dump of $zone" >&2
	echo 'ERROR'
	rm -f $TMP
	exit 1
fi

# Build a list of subzones, one per line.
# This also sorts the records by zone, upper-level zones first.
# The extra "uniq" should stay in here to reduce the number of
# records that domsort must look at, which speeds things up a lot.

awk -f $SUBZONEAWK $TMP | uniq | DOMBIN/domsort -u > $TMP2
rm -f $TMP

# If the query to a nameserver succeeded but awk parsing returns no records,
# then exit normally because there's no subzones in this zone.

lines=`wc -l < $TMP2`
if test $lines -eq 0; then
	rm -f $TMP2
	exit 0
fi

# If recursive, then call ourselves recursively on each subzone.
# If not recursive, then just print all these subzone names.

if $RECURSIVE; then
	for sz in `cat $TMP2`; do
		DOMBIN/subzone -r $sz
	done
else
	for sz in `cat $TMP2`; do
		echo $sz
	done
fi

# Cleanup and exit.

rm -f $TMP $TMP2
exit 0
