#!/usr/bin/perl

use strict;
use warnings;

use CGI qw(param);
use RRDs;

sub print_error {
   print "Content-type: text/html\n\n";
   print "<HTML><BODY>\n";
   print "<H1>ERROR! $ENV{'SCRIPT_NAME'} called with invalid arguments</H1>\n";
   print "</BODY></HTML>\n";
   exit;
}

if (param != "3") {print_error}
my $x = param("x");
my $y = param("y");
my $t = param("t");
my $start;
if (!$y) {print_error}
if (!$t) {print_error}
if (!($x =~ /^[0-9]+$/)) {print_error}
if ($x > "1500") {print_error}
if (!($y =~ /^[0-9]+$/)) {print_error}
if ($y > "1000") {print_error}
if (!($t =~ /^(1day|1week|1month|1year|start)$/)) {print_error}
if ($t eq "start") {
   $start = "1101479107";
} else {
   $start = "-$t";
}
$| = 1; print "Content-type: image/png\n\n";
RRDs::graph ("-",
   "--title", "$t",
   "--start", "$start",
   "--imgformat", "PNG",
   "--width=$x", "--height=$y",
   "DEF:intake=rrd/aquarium_intake.rrd:temp:AVERAGE",
   #"-y 0.1:3",
   #"-A",
   "-E",
   "-Y",
   #"DEF:outflow=rrd/aquarium_outflow.rrd:temp:AVERAGE",
   "GPRINT:intake:MAX:intake  maxtemp %5.2lf",
   "GPRINT:intake:MIN:mintemp %5.2lf",
   "GPRINT:intake:LAST:current %5.2lf\\n",
   #"GPRINT:outflow:MAX:outflow maxtemp %5.2lf",
   #"GPRINT:outflow:MIN:mintemp %5.2lf",
   #"GPRINT:outflow:LAST:current %5.2lf\\n",
   "LINE2:intake#0000FF:intake",
   #"LINE2:outflow#00FF00:outflow"
);
