#!/usr/bin/perl

# this script read one or more databases and extract how many packets are sent and received respectively.
#

$sink1 = 2;
$sink2 = 8;
$sink3 = 12;
$sink4 = 16;

use Mysql;

$hostname = 'idb1.orbit-lab.org';
$user     = 'orbit';
#$database = 'none';
$database= @ARGV; #grid_2006_09_06_14_52_08, grid_2006_09_06_15_29_27,grid_2006_09_06_15_39_09 
$password = 'orbit';
$resultfile ='tempres';


$table2 = "temp/rx_table";

$driver   = 'mysql';

my $noiselevel = 18;
my $now = localtime time;
open(res, ">>$resultfile")
    || die "Can't open result file: $!\n";
print res "$now test results are \n";
close res;

foreach(@ARGV)
{
    dumpDB($_,$table2);
}

system ("awk '\$1~/node$sink1/' $table2 > temp/sink1");
system ("awk '\$1~/node$sink2/' $table2 > temp/sink2");
system ("awk '\$1~/node$sink3/' $table2 > temp/sink3");
system ("awk '\$1~/node$sink4/' $table2 > temp/sink4");

system("gnuplot fairplot.gp");
print "Done. check gnuplot_plot1.ps file! \n";

#we need a subfunction to read 1 database 2 table and dump to two files
sub dumpDB
{
    my ($dbname, $f2) = @_;
    open (OUTFILE2, "> $f2")
    || die "Can't open file to save temporary RX data $!\n";
    my $dbh = Mysql->connect($hostname, $dbname, $user, $password);
    my $sql_query2="SELECT node_id, sequence_no, pkt_seqno, rcvd_pkt_size_sample_sum, rssi, xmitrate  from receiver4_otr_receiverport";

    my $sth2 = $dbh->query($sql_query2);
    while(my @record2 = $sth2->FetchRow) {
	print OUTFILE2 "@record2 \n";
    }
    close OUTFILE2;
}
          



