#!/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 $IMGFMT=lc $CONFIG{"IMAGEFORMAT"};

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

my $FORCE=@ARGV;
my @ITEMS;

# read module-specific settings
#
foreach (HotSaNICparser::read_settings(".")) {
  my ($var,$value)=HotSaNICparser::parse_line($_);
  if ($var eq "DRIVE") {
    $value =~ s/SNMP://;
    push @ITEMS,$value;
    }
  }

my $LEGEND="bytes";

# generate diagrams
#
foreach (@ITEMS) {
  my ($dev,$description)=split /,/;

  $dev =~ s/:.*:/:/;
  (my $name = $dev) =~ s/(\/|:)/_/g;

# if database exists, create images...
  if ( -e "./rrd/$name.rrd") {
    print "creating images for $dev ($description) ...\n";

    foreach my $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);

        ($prints,$xs,$ys)=RRDs::graph $TEMPNAME, "-i", "-b","1024", "-v", $LEGEND,
        "-s","-$fullrange", "-w",$CONFIG{WIDTH}, "-h",$CONFIG{HEIGHT}, "-a", uc($IMGFMT),
        "-l 0", "--alt-autoscale-max", "--title", "free space on $dev - last $descr ($DATESTRING)",
        "DEF:max=rrd/$name.rrd:max:MAX",
        "DEF:used=rrd/$name.rrd:used:AVERAGE",
        "DEF:maxused=rrd/$name.rrd:used:MAX",
        "DEF:minused=rrd/$name.rrd:used:MIN",
        "CDEF:free=max,used,-",
        "CDEF:minfree=max,maxused,-",
        "CDEF:maxfree=max,minused,-",
        "CDEF:minmax=maxused,minused,-",
        "AREA:max#00d000:free",
        "GPRINT:free:AVERAGE:(avg\\:%7.2lf %s$LEGEND",
        "GPRINT:minfree:MIN:min\\:%7.2lf %s$LEGEND)",
        "GPRINT:maxfree:MAX:max\\:%7.2lf %s$LEGEND)\\n",
        "AREA:maxused#d0d000:",
        "AREA:minused#d00000:used",
        "GPRINT:used:AVERAGE:(avg\\:%7.2lf %s$LEGEND",
        "GPRINT:minused:MIN:min\\:%7.2lf %s$LEGEND)",
        "GPRINT:maxused:MAX:max\\:%7.2lf %s$LEGEND)\\n",
        "HRULE:0#000000";
            
        rename $TEMPNAME,$FILENAME;
        printf "  %-7s %d"."x%d %s\n",$descr,$xs,$ys,$FILENAME;

        }
      }
    }
  else { print "  No database found\n  Please check if the daemon is running.\n";next; }
  print "\n";
  }
exit 0;

