#!/opt/bin/perl

#
# rrdgraph.cgi
#
# This script creates a GIF image from a RRD on the fly.
#
# Usage:  rrdgraph.cgi ds=<parametername> history=<daily|weekly|yearly> unit=<unit> 
# Example in HTML: <img src="http://.../rrdgraph.cgi?ds=Aussentemp&history=daily&unit=C">
#
# Michael Dipper, June 2011,  http://dipper.info
# This script is freeware, but a short reference to my page is much appreciated.
#

use POSIX qw(strftime);
use CGI;
use feature qw/say switch/;

$WEBDIR    = "/opt/froeling";       # source directory for RRD database files 
$LOGFILE   = "/var/log/rrd.log";    # log file name
$PORT      = "/dev/ttyUSB0";        # serial port where Lambdatronic is connected
$RRDTOOL   = "/usr/bin/rrdtool";    # path to rrd tool binary		

my $q = new CGI;

chdir $WEBDIR;

# read parameters and protect against injection attacks (input sanitization)
my $parameter = $q->param("ds");
$parameter =~ s/[^A-Za-z0-9]//g;

my $history = $q->param("history");
$history =~ s/[^A-Za-z0-9]//g;

my $unit = $q->param("unit");
$unit =~ s/[^A-Za-z0-9]//g;

my $graph = $q->param("graph");
$graph =~ s/[^A-Za-z0-9]//g;

print "Content-type: image/gif","\n\n";  #MIME header for web server

my $hist;
my $trend;
my $trendstart;

given($history) {
   when(daily) { $hist="-24h"; $trend="32200"; $trendstart="-2 days" }
   when(weekly) { $hist="-144h"; $trend="86400"; $trendstart="-8 days" }
   when(yearly) { $hist="-8760h"; $trend="1724000"; $trendstart="-365 days" }
   default { $hist="-24h"; $trend="12h"; $trendstart="-2 days" }
}

$cmd = "$RRDTOOL graph ${parameter}.gif  --start $hist --end now"
     . " DEF:${parameter}avg=${parameter}.rrd:${parameter}:AVERAGE:start=\'$trendstart\'"
     . " DEF:${parameter}max=${parameter}.rrd:${parameter}:MAX"
     . " DEF:${parameter}min=${parameter}.rrd:${parameter}:MIN"
     . " CDEF:${parameter}trend=${parameter}avg,$trend,TREND"
     . " \'GPRINT:${parameter}avg:LAST:${parameter}\\: %2.1lf ${unit}\'";

given($graph) {
   default {
     $cmd = $cmd
     . " AREA:${parameter}avg#2233AA:average"
     . " LINE1:${parameter}trend#FF0000:trend"
     . ""
   }
}

`$cmd`;

open(GIFILE,"${parameter}.gif") || die "<center>
  <H3>Cannot open gif file.</H3></center>";
while (read(GIFILE, $buf, 8192))
{
   print $buf;
}






