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

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

# size
my $width=700;
my $height=250;
my $currentyear = (localtime)[5] + 1900;
my $copyright = $currentyear .= " © www.tiarora.no";


# read and check query params
my $query=new CGI;
my $interval=$query->param('interval');
$interval='day' unless $interval =~ /hour|day|week|month|year/; 

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

my @opts=("-v", "knots",
"-t Wind/$interval",
"-u 10",
"-l 0",
"-w", $width,
"-h", $height,
"-s", "now - 1 $interval",
"-e", "now",
"-a", "PNG",
"-W", $copyright,
"-D");

RRDs::graph($tmpfile,
  @opts,
  "TEXTALIGN:center",
  "DEF:Wind=$rrd:AWS:MAX",
  "DEF:SOG=$rrd:SOG:MAX",
  "HRULE:11#99FF66::dashes", 
  "HRULE:17#88EE00::dashes", 
  "HRULE:22#CCFF00::dashes", 
  "HRULE:28#EEEE00::dashes", 
  "HRULE:34#FFCC00::dashes", 
  "HRULE:41#FF9900::dashes", 
  "CDEF:F0=Wind,0,1,LIMIT",
  "CDEF:F1=Wind,1,3,LIMIT",
  "CDEF:F2=Wind,3,6,LIMIT",
  "CDEF:F3=Wind,6,10,LIMIT",
  "CDEF:F4=Wind,10,16,LIMIT",
  "CDEF:F5=Wind,16,21,LIMIT",
  "CDEF:F6=Wind,21,27,LIMIT",
  "CDEF:F7=Wind,27,33,LIMIT",
  "CDEF:F8=Wind,33,40,LIMIT",
  "CDEF:F9=Wind,40,47,LIMIT",
  "CDEF:F10=Wind,47,55,LIMIT",
  "CDEF:F11=Wind,55,63,LIMIT",
  "CDEF:F12=Wind,63,100,LIMIT",
  "COMMENT:  ",
  "AREA:F0#F2F2F2FF:F0",
  "AREA:F1#CCFFFFFF:F1",
  "AREA:F2#99FFCCFF:F2",
  "AREA:F3#99FF99FF:F3",
  "AREA:F4#99FF66FF:F4",
  "AREA:F5#CCFF00FF:F5",
  "AREA:F6#FAFA00FF:F6",
  "AREA:F7#FFCC00FF:F7",
  "AREA:F8#FF9900FF:F8",
  "AREA:F9#FF6600FF:F9",
  "AREA:F10#FF3300FF:F10",
  "AREA:F11#AA0000FF:F11",
  "AREA:F12#660000FF:F12",
  "LINE2:SOG#0000FF:SOG",
  "COMMENT:\\s",
  "COMMENT:\\s",
  "COMMENT:\\s",
  "GPRINT:Wind:MIN:Apparent wind in knots\\: Min %2.1lf",
  "GPRINT:Wind:AVERAGE:Average %2.1lf",
  "GPRINT:Wind:MAX:Max %2.1lf",
  "GPRINT:Wind:LAST:Current %2.1lf"

 );

# 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;

