#!/usr/pkg/bin/perl

use strict;
use warnings;

#use Smart::Comments::JSON '##';
use lib 'lib';
use Net::OpenSSH;
use Term::ReadKey;
use SSH::Batch::ForNodes;
use File::Temp qw/ :POSIX /;
use Time::HiRes qw/sleep/;

sub help ($);
sub check_openssh_version ($);

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

my $list_hosts_only = 0;
my ($user, $port, $timeout, $verbose, $ask_for_pass);
my ($ask_for_pass_only_for_sudo, $ask_for_passphrase);
my $concurrency = 20;
my (@cmd, @exprs, $ssh_cmd);
$ssh_cmd = $ENV{SSH_BATCH_SSH_CMD};

my $fetch_value;
my $found_sep;
my $last_option;
my $use_tty;
my $use_quiet_mode;
my $line_mode = $ENV{SSH_BATCH_LINE_MODE};
for (@ARGV) {
    if (defined $fetch_value) {
        $fetch_value->($_);
        undef $fetch_value;
        next;
    }
    if ($_ eq '--') {
        @cmd = @exprs;
        @exprs = ();
        $found_sep = 1;
        next;
    }
    if (/^-(.*)/) {
        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 'w') {
            $ask_for_pass = 1;
        } elsif ($group eq 'W') {
            $ask_for_pass_only_for_sudo = 1;
        } elsif ($group eq 'P') {
            $ask_for_passphrase = 1;
        } elsif ($group eq 'c') {
            $fetch_value = sub { $concurrency = shift };
        } elsif ($group eq 'ssh') {
            $fetch_value = sub { $ssh_cmd = shift };
        } elsif ($group eq 'L') {
            $line_mode = 1;
        } elsif ($group eq 'tty') {
            $use_tty = 1;
        } elsif ($group eq 'q') {
            $use_quiet_mode = 1;
        } else {
            die "Unknown option: $_\n";
        }
        $last_option = $_;
        next;
    }
    push @exprs, $_;
}

if ($ask_for_pass && $ask_for_pass_only_for_sudo) {
    die "ERROR: Option -w should not be used together with -W.\n",
        "Use -w to use passowrd for login and sudo, -W for sudo only.\n";
}

if (defined $fetch_value) {
    die "ERROR: Option $last_option takes a value.\n";
}

if (!$found_sep && !@cmd) {
    push @cmd, shift @exprs;
}
if (!@cmd) {
    die "No command specified.\n";
}

if ($verbose) {
    warn "Command: ", (map { "[$_]" } @cmd), "\n";
    if (defined $ssh_cmd) {
        warn "Using SSH program [$ssh_cmd].\n";
    }
}

check_openssh_version($ssh_cmd || 'ssh');

if ($use_tty) {
    $concurrency = 1;
}

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

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

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 ($passphrase, $password);
if ($ask_for_passphrase) {
    $passphrase = $ENV{SSH_BATCH_PASSPHRASE};
    if (!$passphrase) {
        print STDERR "Passphrase:";
        ReadMode(2);
        while (not defined ($passphrase = ReadLine(0))) {
        }
        ReadMode(0);
        print "\n";
        chomp $passphrase;
    }
    if (!$passphrase) {
        die "No passphrase specified.\n";
    }
} elsif ($ask_for_pass || $ask_for_pass_only_for_sudo) {
    $password = $ENV{SSH_BATCH_PASSWORD};
    if (!$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;
        my $login_with_password = (defined $password) && !$ask_for_pass_only_for_sudo;
        my $ssh = Net::OpenSSH->new(
            $host,
            async => 1,
            defined $timeout ? (timeout => $timeout) : (),
            defined $user ? (user => $user) : (),
            defined $port ? (port => $port) : (),
            defined $passphrase ? (passphrase => $passphrase) : (),
            $login_with_password ? (password => $password) : (),
            defined $ssh_cmd ? (ssh_cmd => $ssh_cmd) : (),
            $use_quiet_mode 
            ? (master_opts => ["-q",], default_ssh_opts => ["-q",],)
            : (),
        );
        if ($ssh->error) {
            if ($line_mode) {
                print STDERR "$host: ";
            } else {
                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({
                (defined $password?
                    (stdin_data => "$password\n") : ()),
            stdout_fh => $out,
            stderr_to_stdout => 1,
            async => 1,
            defined $use_tty ? (tty => 1) : (),
        }, @cmd);
        #warn "PID: $pid\n";
        if (!defined $pid or $pid == -1) {
            $active_count--;
            if ($line_mode) {
                print STDERR "$host: ";
            } else {
                print "===" x 7, " $host ", "===" x 7, "\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;
    }
    if (@pids) {
        my $pid = shift @pids;
        my $host = delete $pid2host{$pid};
        $active_count--;
        if (!$line_mode) {
            print "===" x 7, " $host ", "===" x 7, "\n";
        }
        if (!defined $pid) {
            warn "ERROR: Failed to connect to host $host.\n";
            delete $conns{$host};
            next;
        }
        my $exit = 0;
        my $ret = waitpid($pid, 0);
        $exit = ($? >> 8);

        delete $conns{$host};

        unless ($ret > 0) {
            #redo if ($! == EINTR);
            warn "$host: ERROR: waitpid($pid) failed: $!\n";
            next;
        }

        my $outfile = shift @outs;

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

## HERE...

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

    atnodes [OPTIONS] COMMAND... -- HOST_PATTERN... [OPTIONS]
    atnodes [OPTIONS] COMMAND HOST_PATTERN... [OPTIONS]

OPTIONS:
    -c <num>      Set SSH concurrency limit. (default: 20,
                  when -tty is on, this setting will no use)
    -h            Print this help.
    -l            List the hosts and do nothing else.
    -L            Use the line-mode output format, i.e., prefixing
                  every output line with the machine name.
                  (could be controlled by the env SSH_BATCH_LINE_MODE)
    -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.
    -w            Prompt for password (used for both login and sudo,
                  could be privided by SSH_BATCH_PASSWORD).
    -W            Prompt for password (just for sudo),
                  should not be used with -w.
    -P            Prompt for passphrase (used for login,
                  could be privided by SSH_BATCH_PASSPHRASE).
    -tty          Pseudo-tty.
    -q            Run SSH in quiet mode
_EOC_
    if ($exit_code == 0) {
        print $msg;
        exit(0);
    } else {
        warn $msg;
        exit($exit_code);
    }
}

sub check_openssh_version ($) {
    my $ssh_cmd = shift;

    my $version_info = `$ssh_cmd -V 2>&1`;
    if ($version_info && $version_info =~ /^OpenSSH_(\d+\.\d+)/) {
        my $v = $1;
        if ($v && $v < 4.1) {
            die "OpenSSH version $v, should be >= 4.1!\n";
        }
    }
}

__END__

=encoding utf-8

=head1 NAME

atnodes - Run commands on clusters

=head1 SYNOPSIS

    # run a command on the specified servers:
    $ atnodes $'ps -fe|grep httpd' 'ws[1101-1105].as.com'

    # multiple-arg command requires "--":
    $ atnodes ls /opt/ -- '{ps} + {as}' 'localhost'

    # or use single arg command:
    $ atnodes 'ls /opt/' '{ps} + {as}' 'localhost' # ditto

    # specify a different user name and SSH server port:
    $ atnodes hostname '{ps}' -u agentz -p 12345

    # use -w to prompt for password if w/o SSH key (no echo back)
    $ atnodes hostname '{ps}' -u agentz -w

    # or prompt for password if login and sudo required...
    $ atnodes 'sudo apachectl restart' '{ps}' -w

    # or prompt for password for sudo only...
    $ atnodes 'sudo apachectl restart' '{ps}' -W

    # use -P to prompt for passphrase (no echo back)
    $ atnodes hostname '{ps}' -u agentz -P

    # run sudo command if tty required...
    $ atnodes -tty 'sudo apachectl restart' '{ps}'

    # or specify a timeout:
    $ atnodes 'ping foo.com' '{ps}' -t 3

=head1 USAGE

    atnodes [OPTIONS] COMMAND... -- HOST_PATTERN... [OPTIONS]
    atnodes [OPTIONS] COMMAND HOST_PATTERN... [OPTIONS]

=head1 OPTIONS

    -c <num>      Set SSH concurrency limit. (default: 20,
                  when -tty is on, this setting will no use)
    -h            Print this help.
    -l            List the hosts and do nothing else.
    -L            Use the line-mode output format, i.e., prefixing
                  every output line with the machine name.
                  (could be controlled by the env SSH_BATCH_LINE_MODE)
    -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.
    -w            Prompt for password (used for login and sudo,
                  could be privided by SSH_BATCH_PASSWORD).
    -W            Prompt for password (like -w but conflict, just for sudo.
                  Never use -W together with -w, because -w will be ignored).
    -P            Prompt for passphrase (used for login,
                  could be privided by SSH_BATCH_PASSPHRASE).
    -tty          Pseudo-tty.
    -q            Run SSH in quiet mode

=head1 PREREQUISITES

C<atnodes> (as well as the other scripts bundled by L<SSH::Batch>) requires the OpenSSH I<client> executable (usually spelled "ssh") with multiplexing support (at least OpenSSH 4.1). To check your C<ssh> version, use the command:

    $ ssh -v

On my machine, it echos

    OpenSSH_4.7p1 Debian-8ubuntu1.2, OpenSSL 0.9.8g 19 Oct 2007
    usage: ssh [-1246AaCfgKkMNnqsTtVvXxY] [-b bind_address] [-c cipher_spec]
               [-D [bind_address:]port] [-e escape_char] [-F configfile]
               [-i identity_file] [-L [bind_address:]port:host:hostport]
               [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-R [bind_address:]port:host:hostport] [-S ctl_path]
               [-w local_tun[:remote_tun]] [user@]hostname [command]

There's no spesial requirement on the server side ssh service. Even a non-OpenSSH server-side deamon should work as well.

=head1 DESCRIPTION

Please refer to L<SSH::Batch> for more documentation.

=head1 SEE ALSO

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

=head1 AUTHORS

=over

=item *

Zhang "agentzh" Yichun (章亦春) C<< <agentzh@gmail.com> >>

=item *

Liseen Wan (万珣新) C<< <liseen.wan@gmail.com> >>

=back

=head1 COPYRIGHT & 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.

