#!/usr/bin/perl

use strict;

use gateway_lib;

use IO::File;

use Getopt::Long;

my $ssh_pubkey;
my $ssh_privkey;
my $active;
my $tunnelip;
my $peer;
my $fedkit_dir= "/usr/local/federation";
my $perl = "/usr/bin/perl";
my $iface_file = "/var/emulab/boot/ifmap";
my $ssh = "/usr/bin/ssh";
my $seer;
my $ssh_port = 22;
my @ports;
my $use_file;
my $ssh_privkey;

my %opts = (
    'peer=s' => \$peer,
    'ssh_privkey=s' => \$ssh_privkey,
    'fedkit=s' => \$fedkit_dir,
    'perl=s' => \$perl,
    'ssh=s' => \$ssh,
    'use_file' => \$use_file,
    'seer' => \$seer,
);

exit(20) unless GetOptions(%opts);

if ($use_file) {
    gateway_lib::read_config(gateway_lib::config_filename(), \%opts)
}

my $client = gateway_lib::client_conf_filename();
my $f = new IO::File($client);
my $eid;
my $pid;

while (<$f>) {
    /^ExperimentID:\s+(\S+)/ && do {
	($pid, $eid) = split("/", $1);
    };
}
$f->close();
while (!-e "/proj/$pid/exp/$eid/tbdata/node.pem") {
    print "Waiting for key\n";
    sleep(10);
}

my $cmd = "/usr/bin/scp  -o \"StrictHostKeyChecking no\" " .
    "-i $ssh_privkey /proj/$pid/exp/$eid/tbdata/*.pem $peer:$fedkit_dir/etc";
print "calling $cmd\n";
system($cmd);

my $cmd = "$ssh  -o \"StrictHostKeyChecking no\" -o \"ForwardX11 no\" " .
    "-i $ssh_privkey $peer python /usr/local/seer/experiment-setup.py " . 
    "-F -c 0 Basic &";
print "calling $cmd\n";
system($cmd);

$cmd = "python /usr/local/seer/experiment-setup.py -r control.$eid.$pid -r $peer Basic";
print "Calling $cmd\n";
system($cmd);
