#!/opt/local/bin/perl

use strict;

use Config::Properties;
use Text::ParseWords;
use RRDs;

my $tpls_directory = ".";

opendir TPLS, $tpls_directory or die "Can't open templates directory.\n";
my @templates = grep /\.properties$/, readdir TPLS;
closedir TPLS;

foreach my $tpl (@templates) {
  print "Processing $tpl\n";
  process_templates($tpl);
}

sub process_templates {
  my ($tpl) = @_;
  open my $fh, $tpl or die "Can't open $tpl for reading...\n";
  my $properties = Config::Properties->new();
  $properties->load($fh);
  foreach my $key ($properties->propertyNames) {
    if ($key =~ m/\.command$/) {
      my $name = $1 if $key =~ m/report\.(.+)\.command/;
      my $cmd = $properties->getProperty($key);
      my $columns = $properties->getProperty("report.$name.columns");
      generate_fake_graph($name, $cmd, $columns);
    }
  }
}

sub generate_fake_graph {
  my ($name, $cmd, $csv_cols) = @_;

  print "  Validating template $name\n";

  # Normalize RRD graph command
  $cmd =~ s/^\s+//;
  $cmd =~ s/\s+$//;
  $cmd =~ s/[{]diffTime[}]/86400/g;
  $cmd =~ s/[{]ifSpeed[}]/100000000/g;
  $cmd =~ s/[{]ifHighSpeed[}]/100/g;

  # Define temporary files
  my $rrd_file = "/tmp/fake.rrd";
  my $png_file = "/tmp/fake.png";
  unlink $rrd_file if -e $rrd_file;
  unlink $png_file if -e $png_file;

  # Validate columns and DEF
  my @columns = split /\s*,\s*/, $csv_cols;
  my $def_count = 0;
  my $col_count = scalar(@columns);
  while ($cmd =~ /DEF:\w+=[{]rrd\d+[}]/g) { $def_count++; }
  if ($def_count > $col_count) {
    print "  ERROR($name): Invalid amount of columns($col_count) vs DEF($def_count) entries. Columns: $csv_cols\n\n";
    return;
  }
  if ($def_count == 0) {
    print "  ERROR($name): The graph template doesn't have DEF entries.\n\n";
    return;
  }

  # Validate DS length
  foreach my $c (@columns) {
    if (length($c) > 19) {
      print "  ERROR($name): Invalid DS $c (it has more than 19 characters)\n\n";
      return;
    }
  }

  # Create Fake RRD
  my @create_cmd = ($rrd_file, "--start", "now", "--step", "300");
  foreach my $col (@columns) {
    push @create_cmd, "DS:$col:GAUGE:600:0:U";
  }  
  push @create_cmd, "RRA:AVERAGE:0.5:1:3600";
  RRDs::create(@create_cmd);
  my $err = RRDs::error;
  if ($err) {
    print "  ERROR($name): Cannot create fake RRD: $err\n";
    print "    rrdtool create ", join("\n    ", @create_cmd), "\n\n";
    return;
  }

  # Create Fake Graph
  $cmd =~ s/[{]rrd\d+[}]/$rrd_file/g;
  my @graph_cmd = parse_line('\s+', 1, $cmd);
  unshift @graph_cmd, $png_file;
  my ($result_arr, $xsize, $ysize) = RRDs::graph(@graph_cmd);
  $err = RRDs::error;
  if ($err) {
    print "  ERROR($name): Cannot create fake graph: $err\n";
    print "    rrdtool graph ", join("\n    ", @graph_cmd), "\n\n";
    return;
  }

  print "  OK!\n\n";
}
