#!BOURNESHELL
#	program:	hosttbl
#	purpose:	Build an /etc/hosts type table on stdout.
#			We also append the header and a trailer files.
#			Output is categorized by domain, but sub-categorization
#			is by sorted IP address (first white-spc delimited
#			column).  Any line in the header or trailer with
#			the string "TIMEDATE" on it will be replaced with
#			the output from the "date" cmd.
#	input:		Domain name on command line.
#	output:		/etc/hosts like table generated on stdout
#			or the word "ERROR", with a message on stderr.
#	exit value:	0 if succeeds, 1 if fails (and "ERROR" output).
#
TMP="/tmp/`basename $0`.$$"
TMPPERL="/tmp/`basename $0`-perl.$$"

AWK="DOMLIB/hosttbl.awk"
PERL="DOMLIB/hosttbl.perl"

# Default number of alias levels to generate per host on output.
al="ALIASLEVELS";		# macro substituted from Makefile

if test $# -lt 1 -o $# -gt 2; then
	echo "usage: $0 [aliaslevel] dom.ain." >&2
	exit 1
fi
if test $# -eq 2; then
	al="$1"
	if test x"$al" = x""; then
		echo "usage: $0 [aliaslevel] dom.ain." >&2
		exit 1
	fi
	if test "$al" -lt 0 -o "$al" -gt 99; then
		echo "$0: please keep the alias level small, but no smaller than 0." >&2
		exit 1
	fi
	shift
fi

domain="$1"

# Sanity Check
if test x"$al" = xALIAS""LEVELS; then		# embedded quotes to avoid macro here!
	echo "$0: I haven't been properly installed, see README and Makefile." >&2
	exit 1
fi

HOST=`hostname`
cat DOMLIB/hosttbl.header | \
	sed -e "s/TIMEDATE/`date`/g" | \
	sed -e "s/USER/$USER/g" | \
	sed -e "s/HOST/$HOST/g"

subdomains=`DOMBIN/subdom -r $domain`
if test $? -ne 0; then
	echo "hosttbl: cannot get list of subdomains for $domain" >&2
	echo 'ERROR'
	exit 1
fi

for sd in $subdomains; do
	if test x"$sd" = x"ERROR"; then
		continue
	fi
	echo '#########################################'
	echo "# Hosts in domain $sd"
	echo '#########################################'

# Scan the zone for only three specific types of records:
# SOA records for $sd domain, NS records for $sd domain,
# and any records for anyhost.$sd domain.
	sed -e "s/XXXX/$sd/" $PERL > $TMPPERL
	zone=`DOMBIN/zone $sd`
	DOMBIN/axfr $zone | PERLPROG -n $TMPPERL > $TMP
	if test $? -ne 0; then
		echo "hosttbl: cannot get zone dump of $sd; skipping it." >&2
	else
#echo "DEBUG: working on subdom $sd in zone $zone" >&2
		GAWKPROG -f $AWK -v DOMAIN="$sd" -v ALIASLV="$al" < $TMP | DOMBIN/ipsort
	fi
	echo ''
	rm -f $TMPPERL
done

cat DOMLIB/hosttbl.footer | \
	sed -e "s/TIMEDATE/`date`/g" | \
	sed -e "s/USER/$USER/g" | \
	sed -e "s/HOST/$HOST/g"

rm -f $TMP
exit 0
