#!/usr/bin/env perl

use strict;
use warnings;
use YAML::XS;
use Digest::MD5;

use MYDan::Node;
use MYDan::Util::Sudo;
use MYDan::Agent::Client;
use MYDan::Util::OptConf;

$MYDan::Util::OptConf::THIS = 'agent';

$| ++;

=head1 SYNOPSIS

 $0 -r range user1 user2 ..

 Synchronize keys( id_rsa id_rsa.pub id_dsa id_dsa.pub authorized_keys ) to remote machines

 Only root users can execute

=cut
MYDan::Util::Sudo->sudo();

my $option = MYDan::Util::OptConf->load();
my %o = MYDan::Util::OptConf->load()->get( qw( range=s ) )->dump();
my ( @file, @conf ) = qw( id_rsa id_rsa.pub id_dsa id_dsa.pub authorized_keys );

for my $user ( @ARGV )
{
    next unless my $dir = ( getpwnam $user )[7];
    next unless -d ( $dir = "$dir/.ssh" );

    for my $file ( @file )
    {
        next unless -f ( $file = "$dir/$file" );
        my $cont = `cat $file`;
        push @conf,
        {
            path => $file, chown => $user, file => $cont,
            md5 => Digest::MD5->new()->add( $cont )->hexdigest(),
            chmod => sprintf "%lo", ( stat $file )[2] & 07777,
        } 
    }
}

die "invalid user or user has no key\n" unless @conf;

my %query = ( code => 'sdump', argv => \@conf, sudo => 'root' );
$query{user} = `id -un`;chop $query{user};

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

my %result = MYDan::Agent::Client->new(
    $range->load( delete $o{range} )->list
)->run( %o, query => \%query );

YAML::XS::DumpFile \*STDERR, \%result if %result;
exit 0;