#!/usr/bin/perl
# Authors: Kim Davies and Neale Banks, September 2002.
# Warranty: None whatsoever.
#

use Net::DNS;

my @comau_ns = ();

sub get_comau_ns() {
	@comau_ns = ();
	my $res = Net::DNS::Resolver->new;
	## $res->nameservers("ns1.ausregistry.NET"); ## DEBUG
	my $query = $res->query("com.au", "NS");
	if ($query) {
		foreach $rr ($query->answer) {
			next unless $rr->type eq "NS";
			push @comau_ns, $rr->nsdname;
			## print "ANS ", $rr->nsdname, "\n"; ## DEDBUG
		}
		foreach $rr ($query->authority) {
			next unless $rr->type eq "NS";
			push @comau_ns, $rr->nsdname;
			## print "AUTH ", $rr->nsdname, "\n"; ## DEDBUG
		}
		## print "Found ", scalar(@comau_ns), " ns recs.\n"; ## DEDBUG
		foreach $comau_ns (@comau_ns) {
			my $comau_soa_count = 0;
			my $res = Net::DNS::Resolver->new;
			$res->nameservers($comau_ns);
			## TODO turn off recursion for this SOA query
			my $query = $res->query("com.au", "SOA");
			if ($query) {
				$comau_soa_count = 0;
				foreach $rr ($query->answer) {
					next unless $rr->type eq "SOA";
					$comau_soa_count++;
					last;
				}
			}
			if ($comau_soa_count) {
				## print "OK: ", $comau_ns, " \n"; ## DEBUG
				return $comau_ns;
			}
		}
	} else {
		print "NS query failed: ", $res->errorstring, "\n";
	}
	# Eek, something wrong...
	return "";
}

my $mynsmask = '^.*?\.net\.net\.au$'; ### << -- EDIT THIS ***

my $parentauthority = get_comau_ns();
unless ($parentauthority) {
	die "Could not establish parent authority\n";
}
print "Using: ", $parentauthority, "\n"; ## debug

while (<STDIN>) {
	chomp;
	my $domain = $_;
	my $resolver = Net::DNS::Resolver->new();
	$resolver->nameservers($parentauthority);
	my $packet = $resolver->send($domain.'.', 'NS');
	if ($packet) {
		foreach my $rr ($packet->answer, $packet->authority) {
			if ($rr->type() eq 'NS') {
				if ($rr->nsdname() !~ /$mynsmask/) {
					print "$domain ns ".$rr->nsdname()." does not match mask $mynsmask\n";
				}
			} elsif ($rr->type() eq 'SOA') {
				print "$domain returns soa. probably doesn't exist.\n";
			} else {
				print "odd RR of type ".$rr->type()." in $domain\n";
			}
		}
	} else {
		if ($resolver->errorstring() eq 'NOERROR') {
			print "no records for $domain\n";
		} else {
			print "$domain ns query error ".$resolver->errorstring()."\n";
		}
	}
}
