<%doc>
Fetch DNS and contact information for a given IP address
</%doc>

<%args>
$user
$manager
$ip       => undef
$dns      => undef
$contacts => undef
</%args>

<%init>
use Netdot::REST;
my $rest = Netdot::REST->new(user=>$user, manager=>$manager);
$rest->request($r);
use Apache2::Const -compile => qw(HTTP_UNAUTHORIZED OK NOT_FOUND 
                                  HTTP_BAD_REQUEST HTTP_NOT_ACCEPTABLE);
my %res;
</%init>

<%perl>

if ( $ip ){
    my $ipb = Ipblock->search(address=>$ip)->first;
    unless ( $ipb ) {
	Netdot->throw_rest(code=>Apache2::Const::NOT_FOUND, msg=>"/rest/host_contacts: $ip not found"); 
    }
    unless ( $manager->can($user, 'view', $ipb) ){
	$rest->throw(code=>Apache2::Const::HTTP_FORBIDDEN, 
		     msg=>"User not allowed to view this IP");
    }
    $res{address} = $ipb->address;

    if ( $dns ){
	foreach my $ar ( $ipb->a_records ){
	    my $rr = $ar->rr;
	    my $fqdn = $rr->get_label;
	    if ( $rr->txt_records ){
		push @{$res{name}{$fqdn}{txt}}, map { $_->txtdata } $rr->txt_records;
	    }
	    if ( my $hinfo = $rr->hinfo_records->first ){
		$res{name}{$fqdn}{hinfo}{cpu} = $hinfo->cpu;
		$res{name}{$fqdn}{hinfo}{os}  = $hinfo->os;
	    }
	    if ( my @cnames = RRCNAME->search(cname=>$fqdn) ){
		foreach my $cname ( @cnames ){
		    push @{$res{name}{$fqdn}{cname}}, $cname->rr->get_label;
		}
	    }
	    $res{name}{$fqdn}{info} = $rr->info;
	}
	if ( my $dhcp = $ipb->dhcp_scopes->first ){
	    $res{ether}     = $dhcp->physaddr->address;
	    $res{ethertype} = $dhcp->physaddr->vendor;
	}
    }

    if ( $contacts ){
	my %clists;
	if ( my $subnet = $ipb->parent ){
	    $res{subnet} = $subnet->get_label;
	    if ( $subnet->used_by && (my $cl = $subnet->used_by->contactlist) ){
		$clists{$cl->id} = $cl;
	    }
	    if ( my @ss = $subnet->sites ){
		foreach my $ss ( @ss ){
		    my $site = $ss->site;
		    if ( my $scl = $site->contactlist ){
			$clists{$scl->id} = $scl;
		    }
		    foreach my $ents ( $site->entities ){
			my $e = $ents->entity;
			foreach my $key ( qw(name aliases) ){
			    $res{entities}{$e->id}{$key} = $e->$key;
			}
			if ( $e->availability ){
			    $res{entities}{$e->id}{availability} = $e->availability->name;
			}
			if ( my $ecl = $e->contactlist ){
			    $clists{$ecl->id} = $ecl;
			}
		    }
		}
	    }
	    foreach my $cl ( values %clists ){
		$res{contact_list}{$cl->id}{name} = $cl->name;
		foreach my $con ( $cl->contacts ){
		    my $person = $con->person;
		    foreach my $key ( qw(lastname firstname aliases position email 
                                         office cell home pager ) ){
			$res{contact_list}{$cl->id}{contacts}{$con->id}{$key} = $person->$key;
		    }
		    $res{contact_list}{$cl->id}{contacts}{$con->id}{type} = $con->contacttype->name;
		    $res{contact_list}{$cl->id}{contacts}{$con->id}{employer} = $person->entity->name 
			if $person->entity;
		}
	    }
	}
    }
}

$m->clear_buffer;
$rest->print_serialized(\%res) if %res;

</%perl>
