#!/usr/bin/perl -w
# 
# $Id: host-address-resolver.pl,v 1.1 2002/01/04 13:26:09 fpmip Exp $
#
# Daemon which gets XML agent reports and status from designated drop 
# directories.  The data are then put in a postgres database for further
# analysis.

# Author : Tycho Fruru <tycho@fruru.com>

# Copyright (C) 2001 Tycho Fruru <tycho@fruru.com>
# Copyright (C) 2001 Conostix S.A. Luxembourg - Tycho Fruru <tycho@conostix.com>

# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.  See <http://www.fsf.org/copyleft/gpl.txt>.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
# for more details.
#

use DBI;
use Socket;

DBI->trace(0);

$dbh = DBI->connect("dbi:Pg:dbname=ipfc","","");
$dbh->{AutoCommit} = 0;

$sth=$dbh->prepare("select event_id,src_host from events_with_src_host ".
		   "where src_host IS NOT NULL and not exists (".
		     "select event_id from host_addresses as ha where ".
		       "ha.event_id = event_id)");
$sth->execute;

$sth2=$dbh->prepare("insert into host_addresses ".
		     "(event_id,host_address,host_name) values (?,?,?)");

my $current_event_id;
my $current_src_host;
while (($current_event_id,$current_src_host) = $sth->fetchrow_array) {
#	print "$current_event_id , $current_src_host \n";
	if ($current_src_host =~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/) {
		# it is an IP address
		my $iaddr = inet_aton($current_src_host);
		my $name = gethostbyaddr($iaddr, AF_INET);
		print "Done it : $current_src_host, $name \n";
		$sth2->execute($current_event_id,$current_src_host,$name);
		$sth2->finish;
	} else {
		# it is a hostname
		my ($name,$aliases,$addrtype,$length,@addrs) = gethostbyname($current_src_host);
		
		print "Done it : $current_src_host, $addrs[0] \n";
	}
}

$sth->finish;
$dbh->commit;
$rc = $dbh->disconnect;
