package nmap;

use warnings;
use strict;

use XML::Simple;
use Data::Dump qw/dump/;

use client;

sub scan {
	my $what = shift;

	my $path = $what;
	$path =~ s{[^\w\d\.]+}{_}g;

	warn "# scan $what";

	system("nmap -O -oX /tmp/$path $what") == 0 || return;

	my $nmap = XMLin(
		"/tmp/$path",
		KeyAttr => { address => 'addrtype' },
		ForceArray => [ 'host', 'osmatch', 'port' ],
	);

	my $count = 0;

	foreach my $host ( @{ $nmap->{host} } ) {

		warn dump( $host );

		my $ip  = $host->{address}->{ipv4}->{addr} || die "ipv4";
		my $mac = $host->{address}->{mac}->{addr}  || die "mac";

		print "$ip\t$mac\n";

		client::save_ip_mac( $ip, $mac );
		if ( my $os = $host->{os}->{osmatch}->[0]->{name} ) {
			client::conf( $ip, 'os' => $os );
		}

		my @ports = map { $_->{portid} } @{ $host->{ports}->{port} };
		client::conf( $ip, 'ports' => join("\n", @ports) ) if @ports;

		$count++;
	}

	warn "# finish $count hosts";

	return $count;
}

1;
