#!/usr/bin/perl

# update IPName being null with in-addr.arpa name

use Socket;

$find_null="
select IPID,IPText 
from IP
where IPcountry = NULL;
";

$tempfile="/tmp/sql.$$";
open(SQL,">$tempfile")||die;
print SQL $find_null;
close SQL;

open(SQLOUT,"cat $tempfile | psql|") || die;
<SQLOUT>;
<SQLOUT>;
while(<SQLOUT>) {
    /^\s*(\d+)\s*\|\s*(\S+)/ || last;
    $id=$1; $ipnr=$2;
    $seen{$ipnr}++ and die("Duplicate IP-address in table IP");
    $iaddr = inet_aton($ipnr);
    $name  = gethostbyaddr($iaddr, AF_INET);
    if(not $name) {
	# No DNS for this. Try traceroute
	my @traceroute = `mtr --report -c 1 $ipnr`;
	for (reverse @traceroute) {
	    # Take the last hop that resolves
	    /^\d+\.\d+\.\d+\.\d+\s*/ and next;
	    /^\?\?\?/ and next;
	    chomp;
	    /^(\S+)/ || die;
	    $router=$1;
	    $router=~/^HOST/ and next; # Bug in mtr sometimes gives nothing
	    $name="traceroute/$ipnr/$1" and last;
	}
    }
    if($name=~s/\.?([^.]+)\.([^.]+)$//) {
	$domain = $1; $country = $2;
	print "update IP 
        SET IPName = '$name', IPdomain='$domain', IPcountry='$country'
	where IPID = $id;\n";
    } else { warn("$name does not have domain"); }
}
close SQLOUT;
unlink $tempfile;
