#!/usr/bin/env perl

=head1 SYNOPSIS

 $0 [--src src-range(default `hostname`)] --dst dst-range --sp src-path [--dp dst-path] \
    [--timeout seconds(default 300)]
    [--max number(default 128)]
    [--retry number(default 2)]
    [--gave number(default 3)]

    [--user username(default `id -un`)] 
    [--sudo user1 ] 
    [--chown root]
    [--chmod 777]
    [--cc]

     -1      Forces mrsync to try protocol version 1
     -2      Forces mrsync to try protocol version 2

=cut
use strict;
use warnings;
use Sys::Hostname;

use MYDan::Node;
use MYDan::Agent::Mrsync;
use MYDan::Util::OptConf;

$| ++;

@MYDan::Util::OptConf::CONF = qw( pass_through no_ignore_case );

my $option = MYDan::Util::OptConf->load();
my %o = $option->set( retry => 2, timeout => 300, gave => 3, src => hostname() )
    ->get( qw( src=s dst=s sp=s dp=s timeout=i max=i retry=i nice=i user=s sudo=s gave=i chown=s chmod=s cc 1 2 ) )
    ->dump();

$o{delete $o{ProtocolVersion}} = 1 unless $o{ProtocolVersion} && $o{ProtocolVersion} =~ /^\d$/ && grep{ $o{$_} }1..2;

$option->assert( qw( src dst sp ) );

$o{user} = `id -un` and chop $o{user} unless $o{user};

my $range = MYDan::Node->new( $option->dump( 'range' ) );

map { $o{$_} = [ $range->load( delete $o{$_} || [] )->list ] } qw( src dst );

if( ! defined $o{dp} || ( $o{dp} eq $o{sp} ) )
{
    my %src = map{ $_ => 1 }@{$o{src}};
    die "'$o{sp}' are the same file on same host.\n" unless grep{ ! $src{$_} }@{$o{dst}};
}

my $mrsync = MYDan::Agent::Mrsync->new
(
    ( map { $_ => delete $o{$_} } qw( sp dp src dst 1 2 ) ),
    ( map { $_ => $o{$_} } qw( user sudo ) )
);

exit 0 unless my @failed = $mrsync->run( %o )->failed();
die $range->load( \@failed )->dump . ": failed.\n\n";