#!/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 @ports;
my $fedkit_dir= "/usr/local/federation";
my $perl = "/usr/bin/perl";
my $iface_file;
my $ssh = "/usr/bin/ssh";
my $use_file;
my $ssh_port=22;
my %opts = (
    'ssh_pubkey=s' => \$ssh_pubkey,
    'ssh_privkey=s' => \$ssh_privkey,
    'tunnelip' => \$tunnelip,
    'peer=s' => \$peer,
    'port=s', \@ports,
    'fedkit=s' => \$fedkit_dir,
    'perl=s' => \$perl,
    'ssh=s' => \$ssh,
    'ssh_port=s' => \$ssh_port,
    'use_file' => \$use_file,
);

exit(20) unless GetOptions(%opts);

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

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 $?;

foreach my $p (@ports) {
    my ($type, $port, $host, $eport) = split(":", $p);
    $eport = $port unless $eport;
    my $fopt =  ($type eq 'local'  ? "-L" : "-R") . " :$port:$host:$eport";
    my $cmd = "$ssh -N $fopt -p $ssh_port -o \"StrictHostKeyChecking no\" " .
	"-i $ssh_privkey $peer &";
    system($cmd);
    die if $?;
}

exit(0);

=pod

=head1 NAME

B<port_forward.pl> - Do ssh service port forwarding.

=head1 OPTIONS

=over 8

=item B<fedkit=>I<install_dir>

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

=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<port=>I<port_spec>

Forward the given port.  Each port is given as type:lport:host:rport where
type can be "local" or "remote".  These correspont to B<-L> and B<-R> ssh
port forwarding, respectively.  The remaining parameters are exactly as for
those parameters to ssh.

=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

=item B<use_file>

If given read additional parameters from the file in
/proj/I<project>/exp/I<experiment/tmp/I<hostname>.gw/conf where those are the
current testbed project and experiment and the hostname is before the first
dot.  The file is option: value.


=back

=head1 SYNOPSIS

In addition to providing the key initialization and DETER routing setup for a
gateway without external access as B<active_config.pl> does, B<forward_port.pl>
forwards the given ports using ssh.  B<forward_port.pl> does not establish low 
level connectivity tunnels.


=head1 AUTHORS

Ted Faber <faber@isi.edu>

=cut
