#!/usr/bin/env perl

use strict;
use warnings;

use YAML::XS;
use MYDan::Node;
use MYDan::Util::MIO::SSH;
use MYDan::Util::OptConf;
use MYDan::Util::Pass;
use MYDan::VSSH::Print;

$| ++;

$MYDan::Util::OptConf::ARGC = -1;
@MYDan::Util::OptConf::CONF = qw( pass_through ignore_case );
$MYDan::Util::OptConf::THIS = 'util';

=head1 SYNOPSIS

 $0 -r range [--sudo sudoer] [--noop][--verbose] cmd ..

    [--user user (default `logname`)] 

    [--timeout seconds (default 500)] 
    [--max number (default 128)] \

=cut
my $option = MYDan::Util::OptConf->load();
my %o = $option->get( 
    qw( range=s timeout=i max=i user=s sudo=s noop verbose )
) ->dump();

$option->assert( 'range' );

map { $_ .= '\;' if $_ !~ s/([&|]){2}\s*$/\\$1\\$1/ } @ARGV;

my $range = MYDan::Node->new( $option->dump( 'range' ) );
my %cmd = map { $_ => \@ARGV } $range->load( delete $o{range} )->list();

$o{user} = `id -un` and chop $o{user} unless $o{user};
$o{pass} = +{ MYDan::Util::Pass->new( conf => "$o{conf}/pass", range => $range )
    ->pass( [ keys %cmd ] => $o{user} ) } unless $o{noop};
    
my ( %result, %re )= MYDan::Util::MIO::SSH->new( %cmd )->run( %o );

while( my ( $type, $result ) = each %result )
{
    map{ my $t = $_; map{ $re{$_} .= $t } @{$result->{$t}};}keys %$result;
}

MYDan::VSSH::Print::result( 'mssh' => %re );
