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

    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"}*2, "-a", uc($IMGFMT),
          "-l 0", "--title", "$name - last $descr ($DATESTRING)",
					"DEF:all=rrd/$dev:all:AVERAGE",
					"DEF:routers=rrd/$dev:routers:AVERAGE",
					"DEF:cloud=rrd/$dev:cloud:AVERAGE",
					"DEF:default=rrd/$dev:default:AVERAGE",
					"DEF:ra=rrd/$dev:ra:AVERAGE",
					"DEF:rb=rrd/$dev:rb:AVERAGE",
					"DEF:rc=rrd/$dev:rc:AVERAGE",
					"DEF:rd=rrd/$dev:rd:AVERAGE",
					"DEF:re=rrd/$dev:re:AVERAGE",
					"DEF:rf=rrd/$dev:rf:AVERAGE",
					"DEF:rg=rrd/$dev:rg:AVERAGE",
					"LINE2:all#000080:all_routes/10",
					"LINE2:routers#800000:routes 10.33.0.X",
					"LINE2:cloud#008000:10.33 routes",
					"LINE2:default#808080:default_cost/100",
					"LINE2:ra#FF6666:all ospd",
					"LINE2:rb#FF0000:10.33 ospf",
					"LINE2:rc#FFAADD:10.32 ospf",
					"LINE2:rd#AA00AA:10.43 ospf",
					"LINE2:re#FF9900:10.32 routes",
					"LINE2:rf#00FF00:10.43 routes",
					"LINE2:rg#0000FF:bgp /16 routes",
					"HRULE:0#000000";
        rename $TEMPNAME,$FILENAME;
        printf "  %-7s %d"."x%d %s\n",$descr,$xs,$ys,$FILENAME;
        }
      }
    }
print "\n";
exit 0;


