#!/usr/bin/perl
# IP id <49769> time <1215331823116174606> len <1344>
#

use POSIX qw(ceil floor);
use CGI ':standard';
use GD::Graph::lines;
use DBI;
use CGI;
$query = new CGI;
$run_id = $query->param('run_id');
$ip = $query->param('ip');
$timeout = $query->param('timeout');

print "Content-type: text/html\n\n";

$host = "localhost";
$database = "iptvprobe";
$user = "root";
$pw = "";
$connectionInfo="dbi:mysql:$database;$host";

$dbh = DBI->connect($connectionInfo,$user,$pw);
$sth = $dbh->prepare("SELECT MAX(create_date) - MIN(create_date) as runtime, from_unixtime(MIN(create_date)) as create_date_min, from_unixtime(MAX(create_date)) as create_date_max, SUM(ip_pkts_count) as ip_pkts_sum, SUM(bytes_count) as bytes_sum, SUM(lost_ip_pkts) as lost_ip_pkts_sum from stat_bandwidth WHERE run_id=$run_id AND ip=$ip");
$sth->execute();

$rows = 0;
while (my $ref = $sth->fetchrow_hashref()) {
    $rows++;
    $create_date_min = $ref->{'create_date_min'};
    $create_date_max = $ref->{'create_date_max'};
    $ip_pkts_sum = $ref->{'ip_pkts_sum'};
    $bytes_sum = $ref->{'bytes_sum'};
    $lost_ip_pkts_sum = $ref->{'lost_ip_pkts_sum'};
    $runtime = $ref->{'runtime'};
};            
$sth->finish();

if($create_date_min == "NULL" && $create_date_max == "NULL"){
    print "No data for this run id: $run_id";
    exit (0);
};


$mbytes_sum = $bytes_sum/1048576;
$mbytes_sum = sprintf("%.2f", $mbytes_sum); 
$avg_bitrate = ($bytes_sum/$runtime * 8)/1048576;
$avg_bitrate = sprintf("%.2f", $avg_bitrate );


if($timeout eq ""){
    $timeout = 2;
};

# obtain run info
$sth = $dbh->prepare("select id, FROM_UNIXTIME(start_timestamp) as start_timestamp, zond_host, monitoring_host, description FROM runs WHERE id=$run_id");
$sth->execute();
while (my $ref = $sth->fetchrow_hashref()) {
    $start_timestamp = $ref->{'start_timestamp'};
    $zond_host = $ref->{'zond_host'};
    $monitoring_host = $ref->{'monitoring_host'};
    $description = $ref->{'description'};
};

print "<HTML><HEAD><META http-equiv=\"refresh\" content=\"$timeout\"><TITLE>NetUP IPTVProbe run:$run_id. PCR</HEAD>";
print "<img src=\"/cgi-bin/iptvprobe_pcr_graph.pl?run_id=$run_id&ip=$ip\"><br>";

print "<table border=1>";
print "<tr><td>Probe run identification</td><td>$run_id ($zond_host, $description) </td></tr>";
my $sip =  (($ip>>24) & 255) .".". (($ip>>16) & 255) .".". (($ip>>8) & 255) .".". ($ip & 255); 
print "<tr><td>Monitoring IP</td><td>$sip</td></tr>";
print "<tr><td>Start date</td><td>$create_date_min</td></tr>";
print "<tr><td>Last date</td><td>$create_date_max</td></tr>";
print "<tr><td>Working time (sec)</td><td>$runtime</td></tr>";
print "<tr><td>IP packets count</td><td>$ip_pkts_sum</td></tr>";
print "<tr><td>Bytes count</td><td>$bytes_sum ( $mbytes_sum MB)</td></tr>";
print "<tr><td>Average birate </td><td>$avg_bitrate Mbps</td></tr>";
print "<tr><td><font color=red>Lost IP packets</font></td><td>$lost_ip_pkts_sum</td></tr>";
print "</table>";

print "</HTML>";
$dbh->disconnect();
