#!/usr/bin/perl

use Getopt::Std;
use POSIX;

getopts('hd:f:i:',\%opts);
if ($opts{h}) {
	print "
		[-d <date debut (timestamp)>]
		[-f <date fin (timestamp)>]
		-i <interface>
		[-h this help]\n";
		exit 0;
}

my $dateDebut = 0;
$dateDebut = $opts{d} if $opts{d} ne '';
my $dateFin = time();
$dateFin = $opts{f} if $opts{f} ne '';
die '-i option is mandatory (see -h for help)' if not defined $opts{i} or not $opts{i};
my $itf = $opts{i};

open (LOG, "/usr/local/share/monitor/$itf.csv") or die "monitorDevice.pl: can't open /usr/local/share/monitor/$itf.csv";

sub formatByte {
	$n = $_[0];
	my $str = '';
	if ($n>1024*1024*1024) {
		$ns = floor($n/(1024*1024*1024));
		$n -= $ns*1024*1024*1024;
		$str .= $ns.'G ';
	}
	if ($n>1024*1024) {
		$ns = floor($n/(1024*1024));
		$n -= $ns*1024*1024;
		$str .= $ns.'M ';
	}
	if ($n>1024) {
		$ns = floor($n/(1024));
		$n -= $ns*1024;
		$str .= $ns.'K ';
	}
	$str .= $n.' bytes';
}

my $maxOut=0;
my $maxIn=0;
my $totIn=0;
my $totOut=0;
my $avgIn=0;
my $avgOut=0;
my $firstLine=1;
my $lastBoot;
my $lastIn;
my $lastOut;
my @info;
my $nbBoot=0;
while(<LOG>) {
	chop;
	@info = split ';';
	last if $info[0]>$dateFin;
	next if $info[0]<$dateDebut;
	if ($firstLine) {
		$totIn=$info[2];
		$totOut=$info[3];
		$lastBoot=$info[0]-$info[1];
		$lastIn=$totIn;
		$lastOut=$totOut;
		$dateDebut=$info[0]-$info[1];
	} else {
		# a t-on rebooté entre temps ??
		if ($info[0]-$info[1] - $lastBoot>30) { # oui (je compte 30s entre deux boots. Si on met plus, on rate l'info lorsque la machine reboote rapidement)
			$lastBoot = $info[0]-$info[1];
			$totIn+=$info[2];
			$totOut+=$info[3];
			$lastIn=$info[2];
			$lastOut=$info[3];
			$nbBoot++;
		} else {
			if ($info[2]<$totIn) {	# calculer correctement le delta sur l'input
				$totIn += (4294967296-$lastIn) + $info[2];
			} else {
				$totIn+=$info[2]-$lastIn;
			}
			$lastIn=$info[2];
			if ($info[3]<$totOut) {	# et/ou sur l'output
				$totOut += (4294967296-$lastOut) + $info[3];
			} else {
				$totOut+=$info[3]-$lastOut;
			}
			$lastOut=$info[3];
		}
	}
	$firstLine=0;
}
$dateFin=$info[0];
my $duree = ($dateFin-$dateDebut)/(60*60*24);	# en jour
my $avgIn = &formatByte(floor($totIn/$duree));
my $avgOut = &formatByte(floor($totOut/$duree));
$ftotIn=&formatByte($totIn);
$ftotOut=&formatByte($totOut);
my @toto = localtime($dateDebut);
$fdatDeb = $toto[3].'/'.($toto[4]+1).'/'.($toto[5]+1900).':'.$toto[2].'h'.$toto[1].'m';
@toto = localtime($dateFin);
$fdatFin = $toto[3].'/'.($toto[4]+1).'/'.($toto[5]+1900).':'.$toto[2].'h'.$toto[1].'m';
print <<EOF;
Interface $itf input/output
Date : $fdatDeb to $fdatFin (rebooted $nbBoot times)
total : $ftotIn / $ftotOut
average rate : $avgIn / $avgOut per day
EOF

