#!/usr/bin/perl -w

=head1 SYNOPSIS

 $0 -r range [--user username] [--timeout seconds] [--max number] cmd ..

=cut
use strict;
use Hermes;
use MIO::TCP;
use Poros::Query;
use Vulcan::OptConf;

use constant PORT => 12345;

$| ++;

$Vulcan::OptConf::ARGC = -1;

my $option = Vulcan::OptConf->load();
my %o = $option->get( qw( range=s user=s timeout=i max=i ) )->dump();
my %query = ( code => shift, logname => operator(), argv => \@ARGV );

$query{user} = delete $o{user} if $o{user};

my $range = Hermes->new( $option->dump( 'range' ) );
my %result = MIO::TCP
    ->new( map { join ':', $_, PORT } $range->load( delete $o{range} )->list )
    ->run( %o, input => Poros::Query->dump( \%query ) );

my %mesg;
while ( my ( $type, $mesg ) = each %result )
{
    while ( my ( $mesg, $node ) = each %$mesg )
    {
        $mesg =~ s/\n--- \d+$//;
        push @{ $mesg{$type} }, join ': ', $range->load( $node )->dump, $mesg;
    }
}

for my $io ( sort keys %mesg )
{
    print "---\n$io:\n";
    map { print "  $_" } @{ $mesg{$io} };
}

exit 0;

sub operator
{
    my $name = `logname`; chop $name; return $name;
}
