#!/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);

=pod

=head1 NAME

B<active_config.pl> - Configure an active connectivity gateway under the DETER Federation Architecture

=head1 OPTIONS

=over 8

=item B<fedkit=>I<install_dir>

Directory in which this software is installed.  Generally not needed.

=item B<interfaces=>I<interface table>

A list of interfaces to forward data on of the form:

=begin text

iface ip_addr

=end text

The interface is the operating system name of the interface and the IP address
is given in standard dotted decimal notation.  Other characters on a line are
ignored.

=item B<peer=>I<hostname>

The other gateway providing forwarding.

=item B<perl=>I<perl_binary>
 
Location of the perl binary.  Usually unneeded.

=item B<ssh=>I<ssh_binary>

The pathname of the ssh binary.  Unusally unnecessary.

=item B<ssh_pubkey=>I<keyfile>

A public to install as authorized.

=item B<ssh_privkey=>I<identity_file>

The identity to use for remote access

=item B<tunnelip>

True if the testbed uses the DETER tunnelip extension to provide external
connectivity information

=back

=head1 SYNOPSIS

B<active_config.pl> initiates the active side of the connectivity connection,
which is to say that it:

=over 4

=item *

Installs local keys and reconfigures that local ssh system to do link layer
tunneling.

=item *

Starts a tunnel for each interface in the given interface table, both locally
and remotely.

=back

=head1 AUTHORS

Ted Faber <faber@isi.edu>

=cut
