#!/usr/pkg/bin/perl

use strict;
use warnings;

use lib 'lib';
use Net::OpenSSH;
use Term::ReadKey;
use SSH::Batch::ForNodes;
use File::Temp qw/ :POSIX /;
use File::HomeDir;

sub help ($);

if (!@ARGV) {
    warn "No argument specified.\n\n";
    help(1);
}

my $list_hosts_only = 0;
my ($user, $port, $timeout, $verbose);
my (@exprs);
my $concurrency = 20;
my $fetch_value;
my $ssh_cmd = $ENV{SSH_BATCH_SSH_CMD};
for (@ARGV) {
    if (defined $fetch_value) {
        $fetch_value->($_);
        undef $fetch_value;
        next;
    }
    if (/^-([A-Za-z])(.*)/) {
        if ($2 ne '') {
            die "Unknown option: $_\n";
        }
        my $group = $1;
        if ($group eq 'l') {
            $list_hosts_only = 1;
        } elsif ($group eq 'u') {
            $fetch_value = sub { $user = shift };
        } elsif ($group eq 't') {
            $fetch_value = sub { $timeout = shift };
        } elsif ($group eq 'h') {
            help(0);
        } elsif ($group eq 'p') {
            $fetch_value = sub { $port = shift };
        } elsif ($group eq 'v') {
            $verbose = 1;
        } elsif ($group eq 'ssh') {
            $fetch_value = sub { $ssh_cmd = shift };
        } elsif ($group eq 'c') {
            $fetch_value = sub { $concurrency = shift };
        } else {
            die "Unknown option: $_\n";
        }
        next;
    }
    push @exprs, $_;
}

if (!@exprs) {
    die "No cluster expression specified.\n";
}
my $expr = join ' ', @exprs;

if ($verbose) {
    warn "Cluster expression: $expr\n";
}

my $home = $ENV{SSH_BATCH_HOME} || File::HomeDir->my_home;
if (!defined $home) {
    die "Can't find the home for the current user.\n";
}

my $pubkey_file = "$home/.ssh/id_rsa.pub";
if (-f $pubkey_file) {
    if ($verbose) {
        warn "Found public key file $pubkey_file.\n";
    }
} else {
    my $cmd = "(echo; echo y; echo; echo) | ssh-keygen -q -t rsa";
    if ($verbose) {
        warn "Running command [$cmd]...\n";
    }
    if (system($cmd) != 0) {
        die "Generating SSH key failed.\n";
    }
}

open my $in, $pubkey_file or
    die "Can't open $pubkey_file for reading: $!\n";
my $pubkey = do { local $/; <$in> };
close $in;

SSH::Batch::ForNodes::init_rc();
my $set = SSH::Batch::ForNodes::parse_expr($expr);

if ($set->is_empty) {
    die "No machine to be operated.\n";
}
my @hosts = sort $set->elements;

if ($verbose) {
    warn "Cluster set: @hosts\n";
} elsif ($list_hosts_only) {
    print "Cluster set: @hosts\n";
}

if ($list_hosts_only) {
    exit(0);
}

my $password;
print STDERR "Password:";
ReadMode(2);
while (not defined ($password = ReadLine(0))) {
}
ReadMode(0);
print "\n";
chomp $password;
if (!$password) {
    die "No password specified.\n";
}

my (%conns, @pids, @outs);
my %pid2host;
my $active_count = 0;
while (1) {
    last if !@hosts && !@pids;
    my @active_hosts;
    while ($active_count < $concurrency) {
        last if !@hosts;
        my $host = shift @hosts;
        $active_count++;
        my $ssh = Net::OpenSSH->new(
            $host,
            async => 1,
            defined $timeout ? (timeout => $timeout) : (),
            defined $user ? (user => $user) : (),
            defined $port ? (port => $port) : (),
            password => $password,
            defined $ssh_cmd ? (ssh_cmd => $ssh_cmd) : (),
            master_opts =>  [-o => "StrictHostKeyChecking no"],
        );
        if ($ssh->error) {
            print "===" x 7, " $host ", "===" x 7, "\n";
            warn "ERROR: Failed to establish SSH connection: ",
                $ssh->error, "\n";
            next;
        }
        $conns{$host} = $ssh;
        $active_count++;
        push @active_hosts, $host;
    }

    for my $host (@active_hosts) {
        my ($out, $outfile) = tmpnam();
        my $ssh = $conns{$host};
        my $pid = $ssh->system({
            stdin_data => $pubkey,
            stdout_fh => $out,
            stderr_to_stdout => 1,
            async => 1,
            #tty => 1,
        }, 'if [ ! -d ~/.ssh ]; then mkdir ~/.ssh; fi; chmod 700 ~/.ssh; cat >> ~/.ssh/authorized_keys && chmod 640 ~/.ssh/authorized_keys');
        if (!defined $pid or $pid == -1) {
            $active_count--;
            print "===" x 7, " $host ", "===" x 7, "\n";
            warn "Failed to spawn command.\n\n";
            if ($ssh->error) {
                warn "ERROR: ", $ssh->error, "\n";
            } else {
                warn "ERROR: Failed to spawn command.\n";
            }
            close $out;
            unlink $outfile;
            delete $conns{$host};
            next;
        }
        push @outs, $outfile;
        push @pids, $pid;
        $pid2host{$pid} = $host;
    }

## HERE...

    if (@pids) {
        my $pid = shift @pids;
        my $host = delete $pid2host{$pid};
        $active_count--;
        print "===" x 7, " $host ", "===" x 7, "\n";
        if (!defined $pid) {
            warn "Failed to connect to host $host.\n";
            delete $conns{$host};
            next;
        }
        my $exit = 0;
        my $ret = waitpid($pid, 0);
        if ($ret > 0) {
            $exit = ($? >> 8);
        } else {
            #redo if ($! == EINTR);
            warn "$host: waitpid($pid) failed: $!\n";
            delete $conns{$host};
            next;
        }

        delete $conns{$host};

        my $outfile = shift @outs;

        my $in;
        if (!open $in, $outfile) {
            warn "Can't open $outfile for reading: $!\n";
            next;
        }
        while (<$in>) {
            print;
        }
        if ($exit > 0) {
            warn "Remote command returns status code $exit.\n";
        }
        print "\n";
        close $in;
    }
}

sub help ($) {
    my $exit_code = shift;
    my $msg = <<'_EOC_';
USAGE:

    key2nodes [OPTIONS] HOST_PATTERN... [OPTIONS]

OPTIONS:
    -c <num>      Set SSH concurrency limit. (default: 20)
    -h            Print this help.
    -l            List the hosts and do nothing else.
    -p <port>     Port for the remote SSH service.
    -ssh <path>   Specify an alternate ssh program.
                  (This overrides the SSH_BATCH_SSH_CMD environment.)
    -t <timeout>  Specify timeout for net traffic.
    -u <user>     User account for SSH login.
    -v            Be verbose.
_EOC_
    if ($exit_code == 0) {
        print $msg;
        exit(0);
    } else {
        warn $msg;
        exit($exit_code);
    }
}
__END__

=encoding utf-8

=head1 NAME

key2nodes - Push SSH public keys to remote clusters

=head1 SYNOPSIS

    # push SSH public keys to remote clusters
    $ key2nodes 'ws[1101-1105].as.com'

    $ cat > ~/.fornodesrc
    office=blah.ps.com bloo.ps.com boo[2-25,32,41-70].ps.com

    $ key2nodes '{office}'     # reference cluster var defined
                               # in ~/.fornodesrc

=head1 USAGE

    key2nodes [OPTIONS] HOST_PATTERN... [OPTIONS]

=head1 OPTIONS

    -c <num>      Set SSH concurrency limit. (default: 20)
    -h            Print this help.
    -l            List the hosts and do nothing else.
    -p <port>     Port for the remote SSH service.
    -ssh <path>   Specify an alternate ssh program.
                  (This overrides the SSH_BATCH_SSH_CMD environment.)
    -t <timeout>  Specify timeout for net traffic.
    -u <user>     User account for SSH login.
    -v            Be verbose.

=head1 DESCRIPTION

This script push local F<~/.ssh/id_rsa.pub> file (i.e. the SSH public key) onto the remote server's F<~/.ssh/authorized_keys>. It will chmod F<.ssh> to C<700> and F<.ssh/authorized_keys> to C<640>.

If there's no .ssh directory on the remote server, it will try to create one.

Note that the sh/bash shell is assumed on the remote machines.

When no F<~/.ssh/id_rsa.pub> file found on the local machine, it will invoke
C<ssh-keygen -t rsa> automatically.

=head1 SEE ALSO

L<fornodes>, L<atnodes>, L<tonodes>, L<SSH::Batch>, L<Net::OpenSSH>.

=head1 COPYRIGHT AND LICENSE

This module as well as its programs are licensed under the BSD License.

Copyright (c) 2009, Yahoo! China EEEE Works, Alibaba Inc. All rights reserved.

Copyright (C) 2009, 2010, 2011, Zhang "agentzh" Yichun (章亦春). All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

=over

=item *

Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

=item *

Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

=item *

Neither the name of the Yahoo! China EEEE Works, Alibaba Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

=back

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

