#!/usr/bin/perl
use strict;
use warnings;
use NetAddr::IP;
use Time::Local;
use lib 'scripts';
use MyConfigCDBI;
use Nmap::Scanner;
use Data::Dumper;
$|++;

use constant HOSTS => 100;

MyConfig::CDBI->connection('dbi:SQLite:dbname=config.db');

my @eps = MyConfig::CDBI::Endpoint->search_where(
    { os => \ "IS NULL" },
);

my %list = ();
for my $ep (map { $_->[1] } sort { $a->[0] <=> $b->[0] } 
	    map { [rand, $_] } @eps)
{
    my @addr = MyConfig::CDBI::Assignment->search_where(
	{ endpoint => { '==' => $ep->endpoint } },
	{ order_by => 'time DESC' }
    );
    next unless @addr;
    $list{NetAddr::IP->new($addr[0]->ip)->addr} = $ep;
    last if keys %list == HOSTS;
}

my $scanner = new Nmap::Scanner;
$scanner->tcp_syn_scan(1);
$scanner->add_scan_port('80,25,135,137,139,445,443,110,113,53');
$scanner->guess_os(1);
$scanner->max_rtt_timeout(200);
$scanner->add_target($_) for keys %list;
my $r = $scanner->scan;
my $hl = $r->get_host_list();

while (my $h = $hl->get_next)
{
    my $os = join(', ', 
		  map { join '/', grep { defined $_ } $_->type, $_->vendor, 
			$_->osgen, $_->osfamily, $_->accuracy . '%' } 
		  $h->os->osclasses);
    for my $a ($h->addresses)
    {
	next unless exists $list{$a->addr};
	$list{$a->addr}->os($os);
	$list{$a->addr}->update;
	last;
    }
}
