#!/usr/bin/perl -w
#
# Connect to the DTN telnet console in order to set/unset links availabilities
#
# Arguments :
# link1_name link1_uptime link1_downtime link2 link2_uptime link2_downtime delta
# time arguments must be provided in floating seconds.

use Net::Telnet ();
use Time::HiRes qw ( sleep );


# One argument is missing => die
if(scalar(@ARGV)!=7) {
	die 'Syntax is ./dtn-up-down.pl link1_name link1_uptime link1_downtime link2 link2_uptime link2_downtime delta';
}

# Assign values to variables from command line
my $link1_name=$ARGV[0];
my $link1_uptime=$ARGV[1];
my $link1_downtime=$ARGV[2];

my $link2_name=$ARGV[3];
my $link2_uptime=$ARGV[4];
my $link2_downtime=$ARGV[5];

my $delta=$ARGV[6];


# Parameters defining the access to the DTND console
my $dtnhost="127.0.0.1";
my $dtnport="5050";

# Open socket to DTN console
sub dtnconnect
{
	$dtnconsole = new Net::Telnet (Telnetmode => 0);
	$dtnconsole->open(Host => $dtnhost, Port => $dtnport);

	# Wait for first prompt "dtn%".
	$dtnconsole->waitfor('/dtn\%.*$/');
}

# Change the link status dtnlink($link, $status)
# where $status = "true" or "false"
sub dtnlinkchange
{
	($link, $status) = @_;
	
	$dtnconsole->print("link $status $link");
#	$line = $dtnconsole->getline;
#	die $line unless $line =~ /^.*dtn\%/;
}


# Fork in order to manipulate the two links parameters in //

if ( my $pid = fork) {
    # le père
	
	dtnconnect();
	print("dtnconnect $link1_name\n");
	
	while(1) {
		print("$link1_name open\n");
		dtnlinkchange($link1_name,"open");
		# sleep link1_uptime	
		sleep($link1_uptime);
		
		print("$link1_name close\n");
		dtnlinkchange($link1_name,"close");
		# sleep link1_downtime	
		sleep($link1_downtime);
	
	}
	waitpid( $pid, 0 )
}

else {
	die "duplication impossible : $!" unless defined $pid;

	# processus fils
	
	dtnconnect();
	print("dtnconnect $link2_name\n");
	
	
	# sleep delta
	sleep($delta);
	
	while(1) {
	
		print("$link2_name open\n");
	
		dtnlinkchange($link2_name,"open");
		# sleep link2_uptime
		sleep($link2_uptime);
	
		print("$link2_name close\n");
		dtnlinkchange($link2_name,"close");
		# sleep link2_downtime
		sleep($link2_uptime);
	
	}

	exit 0;
}

