#!/usr/bin/env perl
use strict;
use warnings;
use diagnostics;

use lib "../../lib";
use HotSaNICparser;
use HotSaNICdiagram;
use RRDs;

# read global settings
#
my $MODNAME=HotSaNICparser::get_module_name();
my %CONFIG=HotSaNICparser::get_config("../..");

my $OUTDIR=$CONFIG{"WEBDIR"}."/".lc $MODNAME;
if ( ! -e $OUTDIR ) { mkdir $OUTDIR,0755; }

my $IMGFMT=lc $CONFIG{"IMAGEFORMAT"};
my $TEMPNAME="$OUTDIR/temp.$IMGFMT";

my ($LEGEND,@ITEMS,$name,$range,$descr);
my $IOMIN=500;

my $FORCE=@ARGV;

$LEGEND="accesses";

# generate diagrams
#

opendir DIR,"rrd";
@ITEMS=grep /\.rrd/,readdir DIR;
closedir DIR;

if (! (@ITEMS) ) { print "  No database found\n  Please check if the daemon is running.\n";next; }

# if database exists, create images...
foreach my $dev (@ITEMS) {
	($name=$dev) =~ s/\.rrd//g;
	my $description=$name;
	my $var;
	my $mode;
	my $command;

	print "creating images for $description...\n";

	foreach $range ("1h","6h","1day","1week","1month","1year") {
		my ($descr,$file,$build,$fullrange,$DATESTRING)=HotSaNICdiagram::get_diagram_properties($range);

		my $FILENAME="$OUTDIR/$name-$file.$IMGFMT";

		my $make=$FORCE;
		if ($range eq "1h") { $make++; }
		elsif (! -e "$FILENAME") { $make++; }
		else  {
			my (undef,undef,undef,undef,undef,undef,undef,undef,undef,$mtime,undef,undef,undef) = stat( "$FILENAME" );
			if (time > ($mtime+$build)) { $make++; }
		}

		if ($make>0) {
				my ($prints,$xs,$ys)=RRDs::graph $TEMPNAME, "-i", "-b", "1024",
				"-s","-$range", "-w",$CONFIG{"WIDTH"}, "-h",$CONFIG{"HEIGHT"}, "-a", uc($IMGFMT),
				"-l 0", "--title", "Stats for AS$name - last $descr ($DATESTRING)",
				"DEF:rate=rrd/$dev:rate:AVERAGE",
				"DEF:quality=rrd/$dev:quality:AVERAGE",
				"DEF:signal=rrd/$dev:signal:AVERAGE",
				"DEF:noise=rrd/$dev:noise:AVERAGE",
				"LINE2:rate#000080:Path length",
				"LINE2:quality#800000:",
				"LINE2:signal#008000:",
				"LINE2:noise#808080:",
				"HRULE:0#000000";
				rename $TEMPNAME,$FILENAME;
				printf "  %-7s %d"."x%d %s\n",$descr,$xs,$ys,$FILENAME;
		}
	}
}
print "\n";
exit 0;


