#!/usr/bin/perl
#
# CGI script to create image using RRD graph 
use CGI qw(:all);
use RRDs;
use strict;

# size
my $width=600;
my $height=150;

# path to database
my $rrd='/media/pi/SSD/Data';

# read and check query params
my $query=new CGI;
my $name=$query->param('name');
my $desc=$query->param('desc');
my $interval=$query->param('interval');
my $currentyear = (localtime)[5] + 1900;
my $copyright = $currentyear .= " © www.tiarora.no";


$interval='day' unless $interval =~ /hour|day|week|month|year/; 


# write image into temp file
my $tmpfile="/media/pi/SSD/temp/graphx_$$.png";

	RRDs::graph($tmpfile,
		"-s -1$interval",
		"-t Network traffic/$interval on $name :: $desc",
		"--lazy",
		"--slope-mode",
		"-h", $height, "-w", $width,
		"-l 0",
		"-a", "PNG",
		"-W",$copyright,
		"-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");


# check error
my $err=RRDs::error;
die "$err\n" if $err;

# feed tmpfile to stdout
open(IMG, $tmpfile) or die "can't open $tmpfile\n";
print header(-type=>'image/png', -expires=>'+1m');
print <IMG>;
close IMG;
unlink $tmpfile;

