package dnsd;
 
use warnings;
use strict;

use Net::DNS::Nameserver;
use Net::DNS::Resolver;
use Data::Dump qw/dump/;
use store;

use server;
use client;
our $debug = server::debug;

my $res = Net::DNS::Resolver->new(
#	nameserver => [ '10.60.0.1' ],
	recurse => 1,
	debug => $debug,
);

our ( $ptr_cache, $a_cache );
sub name_ip {
	my ( $name, $ip ) = @_;
	$ptr_cache->{ join('.', reverse split(/\./, $ip)) } = $name;
	$a_cache->{$name} = $ip;
	return $ip;
}

name_ip 'server' => $server::ip;

foreach my $ip ( client::all_ips ) {
	if ( my $name = client::conf( $ip => 'hostname' ) ) {
		name_ip $name => $ip;
	}
}

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

	$debug = server::debug;

	my $audit = {
		qname => $qname,
		qclass => $qclass,
		qtype => $qtype,
		peerhost =>  $peerhost,
		sockhost => $conn->{"sockhost"},
		source => 'unknown',
	};

	$query->print if $debug;

	my $local = $1     if $qname =~ m{^(.+)\.\Q$server::domain\E$};
	   $local = $qname if $qname !~ m{\.};

	my $ttl = 3600;

	if ( $local ) {
		warn "local[$local] $qname $qtype";
		$rcode = "NOERROR";
		my $rdata;
		if ( $qtype eq "A" ) {
			if ( $rdata = $a_cache->{$local} ) {
				$audit->{source} = 'local';
			} else {
				$rcode = "NXDOMAIN";
warn "## no $local in ",dump( $a_cache );
			}
		} elsif ( $qtype eq 'PTR' ) {
			$qname =~ s{\.in-addr\.arpa$}{} || warn "W: can't strip suffix from $qtype $qname";
			if ( my $rdata = $ptr_cache->{$qname} ) {
				$rdata .= '.' . $server::domain;
				push @ans, Net::DNS::RR->new("$qname $ttl $qclass $qtype $rdata");
				$audit->{source} = 'PTR';
			} else {
warn "## no $qname in ",dump( $ptr_cache );
				$rcode = "NXDOMAIN";
			}
		} else {
			$audit->{warn} = "qtype $qtype not supported";
		}

		push @ans, Net::DNS::RR->new("$qname $ttl $qclass $qtype $rdata") if $ttl;

	} elsif ( my $packet = $res->query( $qname, $qtype ) ) {

		$audit->{source} = 'upstream';
		$packet->print;
		push @ans, $_ foreach $packet->answer;
		$rcode = "NOERROR";

	} else {
		# not found
		$rcode = "NXDOMAIN";
	}

	warn "rcode: $rcode ",dump( @ans );

	$audit->{rcode} = $rcode;
	$audit->{ans} = [ map {
		my $data;
		foreach my $n ( keys %$_ ) {
			$data->{$n} = $_->{$n};
		}
		$data;
	} @ans ];

	store::audit( 'response', $audit );

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

sub start {
	my $ns = Net::DNS::Nameserver->new(
		LocalPort    => 53,
		ReplyHandler => sub {
			server->refresh;
			reply_handler(@_);
		},
		Verbose      => $debug,
	) || die "couldn't create nameserver object\n";

	store::audit('start', { port => 53, domain => $server::domain });
	warn "DNS $server::domain";

	$ns->main_loop;
}

1; 
