#!/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-collect collects current traffic data for specified or default interface(s).

 Syntax:
  tc-collect [options]  Collects data from /sys/class/net/*/statistics/?x_bytes
  tc-collect --help     Prints this help text and exits.
  tc-collect --version  Prints the version info and exits.
  
 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(s)  Process given interfaces, not those configured.
  -q               Quiet mode, supressing informative messages.
  -v               Verbose mode, giving more info, can be repeated.
 
 More information on the values for interfaces and dataformat can be found in 
 the config file template /etc/trafficcounter.conf.template.

';

init();

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

for my $interface (@main::interfaceList) {
  ($main::verbosity gt 1) && print "Processing interface ".$interface."\n";

  # check prerequisites
  if (not -e "/sys/class/net/".$interface) { 
    print "WARNING: Skipping interface ".$interface." because there is no /sys/class/net/".$interface."\n";
    next;
  }
  if (not -r "/sys/class/net/".$interface."/statistics/rx_bytes") {
    print "WARNING: Skipping interface ".$interface." because there is no readable /sys/class/net/".$interface."/statistics/rx_bytes\n";
    next;
  }
  if (not -r "/sys/class/net/".$interface."/statistics/tx_bytes") {
    print "WARNING: Skipping interface ".$interface." because there is no readable /sys/class/net/".$interface."/statistics/tx_bytes\n";
    next;
  }

  # collect current data
  my $utcSecs = time();
  my $rxBytes = readCompleteFile("/sys/class/net/".$interface."/statistics/rx_bytes");
  chomp $rxBytes;
  my $txBytes = readCompleteFile("/sys/class/net/".$interface."/statistics/tx_bytes");
  chomp $txBytes;
  my $totalBytes = $rxBytes + $txBytes;
  if ($main::verbosity gt 2) {
    print "Bytes received by ".$interface.": ".$rxBytes." bytes = ".formatTrafficAmount($rxBytes)."\n";
    print "Bytes sent by ".$interface.": ".$txBytes." bytes = ".formatTrafficAmount($txBytes)."\n";
    print "Traffic by ".$interface.": ".$totalBytes." bytes = ".formatTrafficAmount($totalBytes)."\n";
  }

  # collect former data
  my $formerRxBytes = 0;
  my $formerTxBytes = 0;
  my $dataFile = "/var/lib/trafficcounter/".$interface.".traffic";
  if (-e $dataFile) {
    my $lastDataLine="";
    if ($main::verbosity gt 2) { print "Reading existing ".$dataFile."\n"; }
    open (OLDDATA, "<".$dataFile) || die "FATAL: Cannot read ".$dataFile;
    while (my $curLine = <OLDDATA>) {
      #if ($main::verbosity gt 2) { print "Line: '".$curLine."'\n"; }
      #chomp $curLine;
      $lastDataLine = $curLine;
    }
    close OLDDATA;
    chomp $lastDataLine;
    my ($oldUtcSeconds, $oldRxBytes, $oldTxBytes, $oldRxDiff, $oldTxDiff) = split /\t/, $lastDataLine;
    $formerRxBytes = $oldRxBytes;
    $formerTxBytes = $oldTxBytes;
  }
  my $formerTotalBytes = $formerRxBytes + $formerTxBytes;
  if ($main::verbosity gt 2) {
    print "Former count of bytes received by ".$interface.": ".$formerRxBytes." bytes = ".formatTrafficAmount($formerRxBytes)."\n";
    print "Former count of bytes sent by ".$interface.": ".$formerTxBytes." bytes = ".formatTrafficAmount($formerTxBytes)."\n";
    print "Former count of total traffic by ".$interface.": ".$formerTotalBytes." bytes = ".formatTrafficAmount($formerTotalBytes)."\n";
  }
 
  # compute diff
  my $diffRxBytes = 0;
  if ($rxBytes >= $formerRxBytes) {
    $diffRxBytes = $rxBytes - $formerRxBytes; 
  } else {
    if ($main::verbosity gt 1) {
      print "Interface ".$interface." seems to have restarted counting RX bytes.\n";
    }
    $diffRxBytes = $rxBytes;
  }
  my $diffTxBytes = 0;
  if ($txBytes >= $formerTxBytes) {
    $diffTxBytes = $txBytes - $formerTxBytes; 
  } else {
    if ($main::verbosity gt 1) {
      print "Interface ".$interface." seems to have restarted counting TX bytes.\n";
    }
    $diffTxBytes = $txBytes;
  }
  my $diffTotalBytes = $diffRxBytes + $diffTxBytes;
  if ($main::verbosity gt 2) {
    print "New bytes received by ".$interface.": ".$diffRxBytes." bytes = ".formatTrafficAmount($diffRxBytes)."\n";
    print "New bytes sent by ".$interface.": ".$diffTxBytes." bytes = ".formatTrafficAmount($diffTxBytes)."\n";
    print "Total new traffic by ".$interface.": ".$diffTxBytes." bytes = ".formatTrafficAmount($diffTxBytes)."\n";
  }

  # write data
  my $dataLine = join("\t", $utcSecs, $rxBytes, $txBytes, $diffRxBytes, $diffTxBytes);
  if (not -e $dataFile) { 
    $diffTxBytes = 0;
    $diffRxBytes = 0;
    $dataLine = join("\t", "utc_seconds","rx","tx","rx_diff","tx_diff")."\n";
    $dataLine .= join("\t", $utcSecs, $rxBytes, $txBytes, $diffRxBytes, $diffTxBytes);
  }
  open (DATAFILE, ">>".$dataFile) || die "FATAL: Cannot write to $dataFile\n";
  print DATAFILE $dataLine."\n";
  close DATAFILE;

  ($main::verbosity gt 0) && print "Successfully collected traffic data for interface ".$interface."\n";
}


exit 0;

