#!/usr/bin/perl
#
#

use RRDs;

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

# set values for this run
my $parametr = "$ENV{'QUERY_STRING'}";
my @pairs = split(/&/, $parametr);
my $ip = $pairs[0];

my $stepnum =1; 
my $stepsize = 3600;
my $period = "hour";
my $period = $pairs[1];
my $verbose = $pairs[2];

if ($period eq "hour")  { $stepnum = 6 		; $stepsize = 600; };
if ($period eq "6h")    { $stepnum = 6		; $stepsize = 3600; };
if ($period eq "day")   { $stepnum = 24		; $stepsize = 3600; };
if ($period eq "week")  { $stepnum = (7  * 24)	; $stepsize = 3600; };
if ($period eq "month") { $stepnum = (30 * 24)	; $stepsize = 3600; };
if ($period eq "year")	{ $stepnum = (365* 24)	; $stepsize = 3600; };

my $logdir = "/opt/HotSaNIC/modules/networks/rrd/";
my $logfile = "int$ip.rrd";
my $cf = "AVERAGE";
my $ltime = localtime;
my $time = time;
my $endtime = int($time/$stepsize) * $stepsize;
my $starttime = $endtime - ($stepsize * ($stepnum - 1)); 

my ($start,$step,$names,$data) = RRDs::fetch ("$logdir$logfile", "$cf", "-r $stepsize", "-s $starttime", "-e $endtime"); 
my $ERR=RRDs::error;
if ( $verbose > 0) {
print "<HTML><HEAD><META HTTP-EQUIV=Pragma CONTENT=no-cache></HEAD><BODY>\n";
print "ERROR while updating mydemo.rrd: $ERR\n </BODY></HTML>" if $ERR;
print "<pre>";
print "Start:   $period $stepsize $stepnum    ", scalar localtime($start), " ($start)\n";
print "Step size:   $step seconds\n";
print "DS names:    ", join (", ", @$names)."\n";
print "Data points: ", $#$data + 1, "\n";
print "Data:\n";
print "  ", scalar localtime($start), " ($start) \n";
};

$pocetdat = $#$data + 1;
$celkem_in = 0;
$celkem_out = 0;
 foreach my $line (@$data) {
if ( $verbose > 1) {
  print "  ", scalar localtime($start), " ($start) ";
};
  $lasttime = $start;
  $start += $step;
  $pozice = 0;
  foreach my $val (@$line) {
if ( $verbose > 1) {
    printf "%12.1f ", $val;
    printf "%12.1f kB ", ($val * $step * 8);
};
    $pozice += 1;
    if ($pozice == 1) { $celkem_in += $val };
    if ($pozice == 2) { $celkem_in += $val };
    if ($pozice == 3) { $celkem_in += $val };
    if ($pozice == 4) { $celkem_out += $val };
    if ($pozice == 5) { $celkem_out += $val };
    if ($pozice == 6) { $celkem_out += $val };
  }
  if ( $verbose > 1) {
    print "\n";
  };
}
if ( $verbose > 0) {
  print "  ", scalar localtime($lasttime), " ($lasttime) ";
    printf "%12.1f ", $celkem_in/$pocetdat;
    printf "%12.1f MB ", ($celkem_in * $step / 1048576  );
    printf "%12.1f ", $celkem_out/$pocetdat;
    printf "%12.1f MB ", ($celkem_out * $step / 1048576 );
  print "\n";

print "</pre>";
print "<img src=\"../hotsanic/networks/ext$ip-$period.png\">";
print "</BODY></HTML>";
} else {
printf "%12.0f %12.0f ", ($celkem_in * $step ),($celkem_out * $step );
};
