#!/usr/bin/perl
# lets not let the end user see the ssh key, ever.
# need to disable process hiding
use Getopt::Std;

my $ppid;
$ppid = getppid();
$name = `sudo ps -f -p $ppid | tail -1 | awk '{print \$3}'`;
chomp($name);
$name2 = `sudo ps -f -p $name | tail -1`;
chomp($name2);
#if (($name2 !~ /\/usr\/bin\/perl \/bin\/hgcsh|\/usr\/bin\/perl \/opt\/hgcsh\/hgcsh|\/usr\/bin\/perl \/bin\/gsh|\/usr\/bin\/perl \/bin\/eigsh|\/usr\/bin\/perl \/home\/api\/poller.pl/)&&($name2 !~ /test-migmon/))  {
#        print "[*] ERROR: Security violation. Supply this to Patrick Pelanne via Spark please: [$name][$name2]\n";
#        exit;
#}

# connect
my $opt_string = 'p:';
getopts("$opt_string", \%opt );
if ($opt{p}) { $port = $opt{p}; }
else { $port = "22"; }

# run ssh
my $target = $ARGV[0];
my $command = $ARGV[1];
#print "C - $command \n";

# Trying dedicated first so that if that works it won't then send a default key with username to dedi/vps boxes
my $methods = {
    2 => {
        cert_name => 'default',
        cert_cmd  => '/usr/eig/bin/sshca.py',
        cert_file => '~/.ssh/id_rsa-cert.pub',
    },
    1   => {
        cert_name => 'dedicated',
        cert_cmd  => '/usr/eig/bin/sshca.py --dedicated',
        cert_file => '~/.ssh/id_rsa-dedicated.pub',
    },
};

for my $method (sort keys(%{$methods})){
    system($methods->{$method}->{'cert_cmd'});
    my $status = system("ssh","-o","PasswordAuthentication=no", "-o", "StrictHostKeyChecking=no", "-q","-t","-p","$port","-o","CertificateFile=$methods->{$method}->{'cert_file'}","root@" . $target,$command);
    if ($status == 0) {
        last;
    }
}
