#!/usr/bin/perl

#
# Monitors RX bytes and TX bytes using ifconfig for $ARGV interface
#
# creates database for $ARGV interface if it does not exist
# or adds values for actual time
#

if ( $ARGV[0] eq "") { 
    print "usage: rrstats_iface <iface>\n";
    exit 1;
}

$iface = $ARGV[0];					# which iface

require "./rrstats.conf";

$rrdb = $rrdstore.$iface."/base_".$iface;		# rrd for this iface
$wwwdir = $wwwdir.$iface."/";


if ( !( -e "$rrdb.rrd") ) {
	$tm = time;
	# every 600 [s] (10min), 1200s maximum interval between feeding data
	# 1. AVERAGE, every 1st value, store 144 (6*24) values (1day)
	# 2. AVERAGE, every 6th value (each hour), store 720 values (30days)
	# same for MAX values - for MAX upper limit can be a harm :(
	system ("$rrdtoolp create $rrdb.rrd --start $tm -s 600 \\
			    DS:input:COUNTER:1200:U:800000 \\
			    DS:output:COUNTER:1200:U:800000 \\
			    RRA:AVERAGE:0.5:1:144 \\
			    RRA:AVERAGE:0.5:6:720 \\
			    RRA:MAX:0.5:1:144 \\
			    RRA:MAX:0.5:6:720");

#	print "Database created.\n";
	exit;
}

open( IFIN, "$ifcfg $iface |") || die "ifconfig\n";

while (<IFIN>) {
    if ( /RX bytes/ ) {
	chomp;
	@splited = split (" ");
#	print "$splited[1], $splited[2]\n\dfsfd\n";
	($dnn, $rxb) = split(":",$splited[1]);
	($dnn, $txb) = split(":",$splited[5]);
#	print "$rxb $txb\n";
    }
}
close IFIN;

$tm = time;
system("$rrdtoolp update $rrdb.rrd $tm:$rxb:$txb");

if ( $avgmax eq "MAX" ) { 
    $vlabel = "B/10min"; $MB = "1MB/10min" 
} else { 
    $vlabel = "B/s"; $MB = "1Mb/s" 
};


#86400 = 24h
$img = $wwwdir.$iface.".gif";
$size1 = `$rrdtoolp graph $img --start -86400 -X 3 -i -b 1024 \\
		    --vertical-label $vlabel \\
		    DEF:inoctets=$rrdb.rrd:input:$avgmax \\
		    DEF:outoctets=$rrdb.rrd:output:$avgmax \\
		    AREA:inoctets#00FF00:\"Recieved\"  \\
		    LINE1:outoctets#FF0000:\"Transmited\" \\
		    HRULE:100000#0000FF:$MB`;

#25932000 = 30*86400
$img = $wwwdir.$iface.".30d.gif";
$size2 = `$rrdtoolp graph $img --start -2592000 -X 3 -i -b 1024 \\
		    --vertical-label $vlabel \\
		    DEF:inoctets=$rrdb.rrd:input:$avgmax \\
		    DEF:outoctets=$rrdb.rrd:output:$avgmax \\
		    AREA:inoctets#00FF00:\"Recieved\" \\
		    LINE1:outoctets#FF0000:\"Transmited\" \\
		    HRULE:100000#0000FF:$MB`;
