#! /usr/bin/perl


# script to take in an array of iperf log files and then splits out a table


sub iperfCook
{

    my ( @filenames ) = @_;

    print "date\tsource\tsink\tsink_port\tprotocol\tstreams\tsocket_buffer\tduration\tstdev_duration\tbytes_transferred\tstdev_bytes\tlink_utilisation\tstdev_link\tdurations\tbytes_transferred\tlink_utilisations\n";


    foreach my $file (@filenames) {

	my $buffer_size_k;
	my $trans_mbytes;
	my $trans_bandwidth_m;
	my $duration;
	my $numStreams;
	my $protocol;

	my ( $temp, $date, $source, $sink ) = split /_/, $file;
	
	open ( IPERF, "<$file");
	
	while (<IPERF>) {
	    
	    if (/TCP window size: (\d+) Byte/ ) {
		#print "WARNING: " . $1 . "\n";
		$buffer_size = $1 / 2;
	    }

	    # grab first number for indication of stream number
	    # store into array
	    
	    elsif (/(\d+\.?\d*)\-\s*(\d+\.?\d*)\s+sec\s+(\d+)\s+Bytes\s+(\d+)/ ) {
		$time_start = $1;
		$time_end = $2;
		$trans_bytes = $3;
		$trans_bandwidth = $4;
	    }
	    elsif( /TCP\s{1}port\s+(\d+)/ )
	    {
		$remotePort = $1;
	    }

	} #end while
	close ( IPERF );


	my $duration = $time_end - $time_start;
    
	my $buffer_size_k = $buffer_size / 1024;
	my $trans_mbytes = $trans_bytes / ( 1024 * 1024 );
	my $trans_bandwidth_m = $trans_bandwidth / 1000000;
	
	#temp whilst implementing multistreamed polling
	my $numStreams = 1;

	my ( $sourceAdd, $sinkAdd ) = &iperfGetIPs( $source, $sink );
	my $protocol = 'tcp';

	print( "$date\t$source:$sourceAdd\t$sink:$sinkAdd\t$remotePort\t$protocol\t$numStreams\t$buffer_size_k\t$duration\t0.0\t$trans_mbytes\t0.000\t$trans_bandwidth_m\t0.000\t$duration\t$trans_mbytes\t$trans_bandwidth_m");
	print "\n";

    }
    
}




sub iperfGetIPs {

    local ( $source, $sink ) = @_;

    # find out the IP addresses of source and destination
    my ($true_name,$aliases,$addrtype,$addrlength,@addrs) = gethostbyname($source);
    if (!defined $true_name) {
	print STDERR "+++Data_GetIPs: Error! Can not resolve $source to IP address\n";
    }
    else {
	($a, $b, $c, $d) = unpack('C4', $addrs[0]);
	$src_ip = "$a.$b.$c.$d";
    }
    
    my ($true_name,$aliases,$addrtype,$addrlength,@addrs) = gethostbyname($sink);
    if (!defined $true_name) {
	print STDERR "+++Data_GetIPs: Error! Can not resolve $sink to IP address\n";
    }
    else {
	($a, $b, $c, $d) = unpack('C4', $addrs[0]);
	$sink_ip = "$a.$b.$c.$d";
    }
    
    if ( $_debug eq 10 ) {
	print "+Data_GetIPs: source ip: " . $src_ip . "\t" . "sink ip: " . $sink_ip . "\n";;
    }
    
    return my @ips = ($src_ip, $sink_ip);
    
}




1;
