#!/usr/bin/perl -w
use strict;
use RRDs;

my $rrd = '/var/lib/rrd';
my $img = '/var/www/localhost/htdocs/rrdtool/networks';

# process data for each interface (add/delete as required)
&ProcessInterface("eth0", "local network");
&ProcessInterface("eth1", "internet gateway");
&ProcessInterface("ppp0", "internet");
&ProcessInterface("ath0", "wireless");

sub ShowErr
{
	if (my $err = RRDs::error) {
		print "$0: failed to create rrd: $err\n";
	}
}

sub ProcessInterface
{
	my ($name, $desc) = @_;

	my $input = `ifconfig $name`;
	my ($in) = ($input =~ /RX bytes:(\d+)/);
	my ($out) = ($input =~ /TX bytes:(\d+)/);

	print "$name traffic in, out: $in, $out\n";

	if (! -e "$rrd/$name.rrd")
	{
	print "creating rrd database for $name interface...\n";
	RRDs::create "$rrd/$name.rrd",
		"-s 300",
		"DS:in:DERIVE:600:0:12500000",
		"DS:out:DERIVE:600:0:12500000",
		"RRA:AVERAGE:0.5:1:576",
		"RRA:AVERAGE:0.5:6:672",
		"RRA:AVERAGE:0.5:24:732",
		"RRA:AVERAGE:0.5:144:1460";
	&ShowErr();
	}

	RRDs::update "$rrd/$name.rrd",
		"-t", "in:out",
		"N:$in:$out";
	&ShowErr();

	my @intervals = ('day', 'week', 'month', 'year');
	foreach my $time (@intervals) {
	&CreateGraph($name, $time, $desc);
	}
}

sub CreateGraph
{
	my ($name, $interval, $desc) = @_;

	RRDs::graph "$img/$interval/$name.png",
		"-s -1$interval",
		"-t traffic on $name :: $desc",
		"--lazy",
		"-h", "80", "-w", "600",
		"-l 0",
		"-a", "PNG",
		"-v bytes/sec",
		"DEF:in=$rrd/$name.rrd:in:AVERAGE",
		"DEF:out=$rrd/$name.rrd:out:AVERAGE",
		"CDEF:out_neg=out,-1,*",
		"AREA:in#32CD32:Incoming",
		"LINE1:in#336600",
		"GPRINT:in:MAX:  Max\\: %5.1lf %s",
		"GPRINT:in:AVERAGE: Avg\\: %5.1lf %S",
		"GPRINT:in:LAST: Current\\: %5.1lf %Sbytes/sec\\n",
		"AREA:out_neg#4169E1:Outgoing",
		"LINE1:out_neg#0033CC",
		"GPRINT:out:MAX:  Max\\: %5.1lf %S",
		"GPRINT:out:AVERAGE: Avg\\: %5.1lf %S",
		"GPRINT:out:LAST: Current\\: %5.1lf %Sbytes/sec",
		"HRULE:0#000000";
	&ShowErr();
}
