#!/bin/sh
#	program:	zone
#	release:	1.5.0
#	input:		domain name on command line,
#			optional nameserver to direct queries to.
#	output:		the name of the zone within which this domain exists,
#			or the word "ERROR" (distinguishable from a real
#			record because it has no period on the end).
#			If error occurs, stderr describes it.
#	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.
#

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

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

# Find the zone for this domain by trying domains "dom.ain.", "ain.", "."
# If none of these domains has an SOA record, we must fail.

soa=
zone="$domain"
keepgoing=true
while $keepgoing; do
	soa=`/usr/local/domtools/bin/soa $nameserver $zone 2>/dev/null`
	status=$?
	if test $status -ne 0 -o x"$soa" = x""; then
		zone=`/usr/local/domtools/bin/basedomain $zone`
		basestatus=$?
		if test $basestatus -ne 0; then
			keepgoing=false
		fi
	else
		keepgoing=false
	fi
done

if test $status -ne 0 -o x"$soa" = x""; then
	echo "$0: could not figure out what zone $domain is in." >&2
	echo 'ERROR'
	exit 1
fi

echo $zone
exit 0
