#!/usr/bin/perl 

use strict;

use Net::DNS;
use Net::DNS::Resolver;

my $res=Net::DNS::Resolver->new();
die "no $res !" unless defined($res);
$res->searchlist(); ## make it empty
print "Nameservers used : ".join(" ",$res->nameservers())."\n";

while(defined(my $l=<STDIN>))
{
 chomp($l);
 my ($name,$ip)=(split(/\s+/,$l));
 my ($dom)=($name=~m/\.([^\.]+\.[^\.]+)$/);

 print "$name / $ip : ";

 my $packet=$res->query($dom,"NS");

 unless (defined($packet))
 {
  print " unable to query for NS\n";
  next;
 }

 my @a=$packet->answer(); ## list of answers, Net::DNS::RR objects
 my $ok=0;
 my @ns;
 foreach my $a (@a)
 {
#  print $a->name()." ".$a->type()." ".$a->class()." ".$a->ttl()." ".$a->rdatastr()." ".$a->nsdname()."\n";
  next unless ((uc($a->name()) eq uc($dom)) && ($a->type() eq 'NS')); ## 1 NS record => OK
  push @ns,$a->nsdname();
  $ok=1;
 }

 unless ($ok)
 {
  print " ERROR [1]\n";
  next;
 }

 print @ns." NS ";
 my %r;
 $ok=1;
 my $bh=0;
 foreach my $ns (@ns)
 {
  $res->nameservers($ns); ## we will query $ns
  my $p=$res->query($name,"A","IN");
  unless (defined($p))
  {
   print "<$ns NOREPLY> ";
   $bh++;
   next;
  }
  my @a=$p->answer();
  my $h=$p->header();
  unless ($h->aa()) ## not authoritative ??
  {
   print "<$ns non-authoritative> ";
   $bh++;
   next;
  }
  unless (defined(@a) && (@a))
  {
   push @{$r{2}},$ns;
   $ok=0;
   next;
  }

  foreach my $a (@a)
  {
#   print $a->name()." ".$a->type()." ".$a->address()."\n";
   next unless ((uc($a->name()) eq uc($name)) && ($a->type() eq 'A')); 
   next if ($a->address() eq $ip);
   push @{$r{3}},$ns;
   $ok=0;
  }

 } ## fin du foreach

 if (keys(%r))
 {
  while(my ($k,$v)=each(%r))
  { 
   foreach my $ns (@$v)
   {
    print "<$ns [$k]> ";
   }
  } ## fin du while sur %r
 }

 if ($bh==@ns)
 {
  print "LAME DELEGATION [4]";
 }

 if ($ok)
 {
  print "OK"; ## ouf...
 }

 print "\n";
} ## fin du while
