#!/usr/bin/perl
#
# $Id$
#
# TrafficCounter by IBCL
#
# Copyleft IBCL 2010
#
# Author: Christoph Lechleitner <lech@ibcl.at>
#


use strict;
use Date::Format;

# centos packages:
# yum install perl-TimeDate 

require("/usr/lib/trafficcounter/tc-functions.pl");

$main::helpMessage='
 tc-report generates traffic reports from data tc-collected previously

 Syntax:
  tc-report [options]  Generates reports from /var/lib/trafficcounter/*.traffic
  tc-report --help     Prints this help text and exits.
  tc-report --version  Prints the version info and exits.
  
 Common tc-* options are:
  -c configfile    Read config from configfile, ignore /etc/trafficcounter.conf
  -d               Debug mode, giving even debug infos.
  -f dataformat    Use given rather than configured dataformat. For testing.
  -i interface     Process interface, not the first of the configured list.
  -q               Quiet mode, supressing informative messages.
  -v               Verbose mode, giving more info, can be repeated.
 
 tc-report specific options are:
  -a         show Average, i.e. Bytes per seconds, instead of sums.
  -B         Generate Brief report. For i.e. daily+ cron jobs.
  -C         Report Current traffic, i.e. over last minutes. For load checks.
  -I infile  Read infile rather than /var/lib/trafficcounter/*.traffic
  -R         Report Recent traffic. This is the default.

 More report options will be added as experience will suggest useful.

 More information on the values for interfaces and dataformat can be found in 
 the config file template /etc/trafficcounter.conf.template.

';
#  -D         Generate Daily report over last 365 days. NYI.
#  -M         Generate Monthly report over last 12 months. NYI.

init("aBCI:R");

#print "tc-collect not implemented yet ;-((\n";

my $dataFile = "";
my $reportType = "";
my $typeOptionCount = 0;
my $showAvg = 0;
if ( $main::opts{"a"} ) {
  $showAvg = 1;
}
if ( $main::opts{"B"} ) {
  $reportType = "brief";
  $typeOptionCount++;
}
if ( $main::opts{"C"} ) {
  $reportType = "current";
  $typeOptionCount++;
}
my $dataFile = $main::opts{"I"};
if ( $main::opts{"R"} ) {
  $reportType = "recent";
  $typeOptionCount++;
}
if ($typeOptionCount > 1) { die "FATAL: Too many report type options specified."; }
if ($reportType eq "") { 
  $reportType = "recent";
}
my $reportTypeOk = 0;
if ($reportType eq "brief")   { $reportTypeOk++; }
if ($reportType eq "current") { $reportTypeOk++; }
if ($reportType eq "recent")  { $reportTypeOk++; }
if ($reportTypeOk < 1) { die "FATAL: Unsupported report type: ".$reportType; }

if ($dataFile eq "") {
  if (scalar (@main::interfaceList) gt 1) {
    if ($main::verbosity gt 0) {
      print "WARNING: tc-report only processes the first interface specified.\n";
    } 
  } 
  my $interface = $main::interfaceList[0];
  $dataFile = "/var/lib/trafficcounter/".$interface.".traffic";
  ($main::verbosity gt 1) && print "Going to process interface ".$interface."\n";
}
if (not -e $dataFile) { die "FATAL: No such file: ".$dataFile; }


my %periodBegins = ();
my %periodEnds = ();
my %periodRxBytes = ();
my %periodTxBytes = ();
my %periodTotalBytes = ();
my @periodKeys = ();

my $now = time();
($main::verbosity gt 2) && print "Now = ".time2str("%Y-%m-%d %H:%M:%S",$now)."\n";

my $lastFullMinute = int($now / 60) * 60;
($main::verbosity gt 2) && print "Last full minute = ".time2str("%Y-%m-%d %H:%M:%S",$lastFullMinute)."\n";

my $lastFullHour = int($now / 3600) * 3600;
($main::verbosity gt 2) && print "Last full hour = ".time2str("%Y-%m-%d %H:%M:%S",$lastFullHour)."\n";

my $lastMidnight = int($now / (3600*24)) * (3600*24); 
($main::verbosity gt 2) && print "Last midnight = ".time2str("%Y-%m-%d %H:%M:%S",$lastMidnight)."\n";
# FIXME time zone requires better calculation

if ($reportType eq "brief") {
  ($main::verbosity gt 1) && print "Generating brief report.\n";
  initPeriod("Last 5 minutes", $lastFullMinute-60*5, $lastFullMinute);
  initPeriod("Last 60 minutes", $lastFullMinute-3600, $lastFullMinute);
  initPeriod("Last 24 hours", $lastFullMinute-3600*24, $lastFullMinute);
  initPeriod("Last 30 days", $lastFullMinute-3600*24*30, $lastFullMinute);
}

if ($reportType eq "recent") {
  ($main::verbosity gt 1) && print "Generating recent traffic report.\n";
  initPeriod("This hour", $lastFullHour, $lastFullMinute);
  initPeriod("Last hour", $lastFullHour-3600, $lastFullHour);
  my $i = 1;
  #while ($lastFullHour-3600*($i+1) > $lastMidnight) {
  while ($i < 24) {
    initPeriod("".$i.". hour before", $lastFullHour-3600*($i+1), $lastFullHour-3600*$i);
    $i++;
  }
  initPeriod("Today", $lastMidnight, $lastFullMinute);
  initPeriod("Yesterday", $lastMidnight-3600*24, $lastMidnight);
  for ($i=1; $i<=7; $i++) {
    initPeriod("".$i.". day before", $lastMidnight-3600*24*($i+1), $lastMidnight-3600*24*$i);
  }
  initPeriod("Last 7 days", $lastMidnight-3600*24*7, $lastMidnight);
  initPeriod("Last 30 days", $lastMidnight-3600*24*30, $lastMidnight);
}

if ($reportType eq "current") {
  ($main::verbosity gt 1) && print "Generating recent traffic report.\n";
  initPeriod("This minute", $lastFullHour, $lastFullMinute);
  my $i = 1;
  #while ($lastFullHour-3600*($i+1) > $lastMidnight) {
  while ($i < 15) {
    initPeriod("".$i.". minute before", $lastFullMinute-60*($i+1), $lastFullMinute-60*$i);
    $i++;
  }
  initPeriod("Last 15 minutes", $lastFullMinute-60*15, $lastFullMinute);
}


open (DATA, "<".$dataFile) || die "FATAL: Cannot read ".$dataFile;
my $lastPeriodUtcSeconds = 0;
my $firstLine = <DATA>; # eats informative column names line
while (my $curLine = <DATA>) {
  #if ($main::verbosity gt 2) { print "Line: '".$curLine."'\n"; }
  chomp $curLine;
  my ($curUtcSeconds, $curRxBytes, $curTxBytes, $curRxDiff, $curTxDiff) = split /\t/, $curLine;
  my $curTotalDiff = $curRxDiff + $curTxDiff;
  if ($main::verbosity gt 2) {
    print "Counting line collected at ".time2str("%Y-%m-%d %H:%M:%S",$curUtcSeconds)."\n";
  }
  # shall we count $curUtcSeconds or the halftime of that period?
  my $periodHalfTime = $curUtcSeconds;
  if ($lastPeriodUtcSeconds gt 0) 
  { $periodHalfTime = ($curUtcSeconds + $lastPeriodUtcSeconds) / 2; }
  if ($main::verbosity gt 2) {
    print "Matching periods based on period half time ".time2str("%Y-%m-%d %H:%M:%S",$periodHalfTime)."\n";
  }
  foreach my $periodKey (@periodKeys) {
    if ( ($periodBegins{$periodKey} lt $periodHalfTime) and 
         ($periodEnds{$periodKey} ge $periodHalfTime) ) {
      #if ($main::verbosity gt 2) { print "Period ".$periodKey." matches.\n"; }
      $periodRxBytes{$periodKey} += $curRxDiff;
      $periodTxBytes{$periodKey} += $curTxDiff;
      $periodTotalBytes{$periodKey} += $curTotalDiff;
    #} else {
    #  if ($main::verbosity gt 2) { print "Period ".$periodKey." does not match.\n"; }
    }
  }
  $lastPeriodUtcSeconds = $curUtcSeconds;
}
close DATA;
 
if ($main::verbosity gt 0) { print "Traffic total (in/out), avg. (in/out) from ".$dataFile.":\n"; }
foreach my $periodKey (@periodKeys) {
  my $periodTotalBytes = $periodRxBytes{$periodKey} + $periodTxBytes{$periodKey};
  my $periodSecs = $periodEnds{$periodKey} - $periodBegins{$periodKey};
  print time2str("%Y-%m-%d %H:%M:%S",$periodBegins{$periodKey})."/".time2str("%Y-%m-%d %H:%M:%S",$periodEnds{$periodKey});
  print ", ";
  print $periodKey.": ";
  if ($showAvg) {
    print formatTrafficAmount(int($periodTotalBytes/$periodSecs))."/s";
    print " (".formatTrafficAmount(int($periodRxBytes{$periodKey}/$periodSecs))."/s in, ";
    print formatTrafficAmount(int($periodTxBytes{$periodKey}/$periodSecs))."/s out)";
  } else {
    print formatTrafficAmount($periodTotalBytes);
    print " (".formatTrafficAmount($periodRxBytes{$periodKey})." in, ";
    print formatTrafficAmount($periodTxBytes{$periodKey})." out)";
  }
  print "\n";
}


exit 0;


sub initPeriod( $ $ $ ) {
  # $1 = key = name
  # $2 = from utc seconds
  # $3 = to utc seconds
  my $key = shift;
  my $begin = shift;
  my $end = shift;
  push @periodKeys, $key;
  $periodBegins{$key} = $begin;
  $periodEnds{$key} = $end;
  $periodRxBytes{$key} = 0;
  $periodTxBytes{$key} = 0;
  $periodTotalBytes{$key} = 0;
  if ($main::verbosity gt 2) {
    print "Initialized counters for '".$key."' from ".time2str("%Y-%m-%d %H:%M:%S",$begin)." until ".time2str("%Y-%m-%d %H:%M:%S",$end)."\n";
  }
}

