#!/usr/bin/perl 

use strict;
use IO::File;
use IO::Pipe;
use Getopt::Long;

my $TMCC = "/usr/local/etc/emulab/tmcc";
my $FINDIF = "/usr/local/etc/emulab/findif";
my $IFCONFIG = "/sbin/ifconfig";
my $ROUTE = "/sbin/route";

my $tmcc = new IO::Pipe || die "Can't create tmcc pipe: $!\n";
my $interface;
my $ip;
my $mac;
my $netmask ="255.255.255.0";
my $router;
my $routedest;

my $os = `uname`;
chomp $os;

GetOptions('destination=s' => \$routedest);

$tmcc->reader("$TMCC tunnelip");
while (<$tmcc>) {
    chomp;
    /TUNNELIP=([\d\.]*)/ && do { $ip = $1; };
    /TUNNELMASK=([\d\.]*)/ && do { $netmask = $1; };
    /TUNNELMAC=([[:xdigit:]]*)/ && do { $mac = $1; };
    /TUNNELROUTER=([\d\.]*)/ && do { $router = $1; };
}
$tmcc->close();

die "No MAC information for tunnel.\n" unless $mac;

$interface = `$FINDIF $mac`;
chomp $interface;
die "Can't get interface for mac address $mac: $?" if $? || !$interface;

my @ifconfig = ($IFCONFIG, $interface, $ip);
push(@ifconfig, 'netmask', $netmask) if $netmask;

system(@ifconfig);
die join(" ", @ifconfig) . " failed: $!\n" if $?;

if ($routedest ) {
    if ($router) {
	my @cmd;

	if ( $os =~ /^Linux/ ) { 
	    @cmd = ($ROUTE, 'add', $routedest, 'gw', $router);
	}
	elsif ( $os =~ /^FreeBSD/ ) {
	    @cmd = ($ROUTE, 'add', $routedest, $router);
	}
	else {
	    die "Unknown OS: $os\n";
	}
	system(@cmd);
	die join(" ", @cmd) . " failed: $?\n" if $?;
    }
    else { die "Destination but no router\n"; }
}
exit(0);
