#!/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", "direction",
"-t Wind direction/$interval",
"-u 360",
"-l 0",
"-w", $width,
"-h", $height,
"-s", "now - 1 $interval",
"-e", "now",
"-y", "60:1",
"-a", "PNG",
"-W", $copyright,
"-A",
"-D");

RRDs::graph($tmpfile,
  @opts,
  "TEXTALIGN:center",
  "DEF:Direction=$rrd:AWA:MAX",
  "CDEF:Stbd=Direction,0,180,LIMIT",
  "CDEF:Port=Direction,181,360,LIMIT",
  "LINE1:Direction#030303:",
  "LINE2:Stbd#00CC00:",
  "LINE2:Port#DD0000:",

 );

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

