#!/bin/sh
#	program:	root
#	release:	1.5.0
#	input:		<none>
#	output:		one or more root domain name servers for the root domain
#			as returned by one of the root domain servers, one per
#			line, 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 $# -ne 0; then
	echo "usage: $0" >&2
	echo 'ERROR'
	exit 1
fi

# I don't like how "doc" requires you to type the parent zone name by hand with each query,
# so we do it better.

rootnslist=`dig . ns +ret=2 +pfset=0x2024 2>/dev/null | /usr/local/domtools/bin/digparse | /usr/local/bin/perl5.00502 -pe 'END{$? = !defined $l} s/^\S+\s+//; s/[\t ]+/ /g; $l++' | awk '{print $2}'`
if test $? -ne 0 -o x"$rootnslist" = x""; then
	rootnslist='C.ROOT-SERVERS.NET. E.ROOT-SERVERS.NET.'		# failsafe, sorta.
fi

domain=.

realrootnslist=''
for ns in $rootnslist; do
	if test x"$realrootnslist" = x""; then
		realrootnslist=`dig @$ns $domain NS +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++' | awk '$1=="NS"{print $2}'`
	fi
done

if test x"$realrootnslist" = x""; then
	echo "$0: None of the root name servers were reachable." >&2
	echo 'ERROR'
	exit 1
fi

for ns in $realrootnslist; do
	echo $ns
done
exit 0
