#!/usr/bin/perl

use strict;

use gateway_lib;

use IO::File;

use Getopt::Long;

my $ssh_pubkey;
my $ssh_privkey;
my $tunnelip;
my $peer;
my $fedkit_dir= "/usr/local/federation";
my $perl = "/usr/bin/perl";
my $iface_file;
my $ssh = "/usr/bin/ssh";

exit(20) unless GetOptions(
    'ssh_pubkey=s' => \$ssh_pubkey,
    'ssh_privkey=s' => \$ssh_privkey,
    'tunnelip' => \$tunnelip,
    'peer=s' => \$peer,
    'fedkit=s' => \$fedkit_dir,
    'perl=s' => \$perl,
    'interfaces=s' => \$iface_file,
    'ssh=s' => \$ssh,
);


my $tunnelparam = $tunnelip ? '--tunnelip' : '';

system("$perl -I$fedkit_dir/lib $fedkit_dir/bin/prep_gateway.pl --peer=$peer " .
    "--ssh_pubkey=$ssh_pubkey $tunnelparam");
exit(20) if $?;

my $f = new IO::File($iface_file) || die "Can't open $iface_file: $!\n";
my $ifnum = 0;

while (<$f>) {
    /([[:alnum:]]+)\s+([\d\.]+)/ && do {
	my ($iface, $addr) = ($1, $2);

	my $cmd = "$ssh -w $ifnum:$ifnum -o \"Tunnel ethernet\" " . 
	    "-o \"StrictHostKeyChecking no\" -i $ssh_privkey " .
	    "$peer perl -I$fedkit_dir/lib $fedkit_dir/bin/setup_bridge.pl " .
	    "--tapno=$ifnum --dest=$addr &";
	system($cmd);
	die if $?;
	gateway_lib::bind_tap_to_iface($ifnum, $iface, $addr);
	$ifnum++;
    };
}
$f->close();
exit(0);
