#!/usr/bin/perl

use warnings;
use Net::DNS;
use Net::DNS::Nameserver;

sub reply_handler {
  my ($qname, $qclass, $qtype, $peerhost,$query,$conn) = @_;
  my ($rcode, @ans, @auth, @add);

  print "Received query from $peerhost to ". $conn->{sockhost}. "\n";
#  $query->print;

#  if ($qtype eq "A" && $qname eq "foo.example.com" ) {
#    my ($ttl, $rdata) = (30, "10.1.2.3");
#    my $rr = new Net::DNS::RR("$qname $ttl $qclass $qtype $rdata");
#    push @ans, $rr;
#    $rcode = "NOERROR";
#  }elsif( $qname eq "foo.example.com" ) {
#    $rcode = "NOERROR";
#  }else

  if($qtype eq "A") {
    my $res = Net::DNS::Resolver->new;
    my $answer = $res->search("$qname");
    my $random_number = rand(100);
    my ($ttl, $rdata);
    my $ip;
    foreach $record ($answer->answer) {
      $ip=$record->address;
    }

    if ($random_number > 50) {
      ($ttl, $rdata) = (30, "205.196.209.62");
    } else {
      ($ttl, $rdata) = (30, "$ip");
    }
    print "$random_number - ".$ip."\n";

    #my ($ttl, $rdata) = (30, "10.1.2.3");
    my $rr = new Net::DNS::RR("$qname $ttl $qclass $qtype $rdata");
    push @ans, $rr;
    $rcode = "NOERROR";
  }else{
	$rcode = "NXDOMAIN";
  }

  # mark the answer as authoritive (by setting the 'aa' flag
    return ($rcode, \@ans, \@auth, \@add, { aa => 1 });
}

my $ns = new Net::DNS::Nameserver(
  LocalPort    => 53,
  ReplyHandler => \&reply_handler,
  Verbose	     => 0
) || die "couldn't create nameserver object\n";

$ns->main_loop;
