#!/usr/bin/perl -wT

use diagnostics;
use constant GRAPH_DIR => "/var/lib/munin/xvm-prod-hosts.mit.edu";
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use RRDs;
use File::Spec::Functions;

our %graph_types = (cpu => "xen_cpu");
our %formats = qw(svg image/svg+xml png image/png eps application/postscript pdf application/pdf);

my @args = (qw(
--font LEGEND:7:/usr/share/munin/VeraMono.ttf
--font UNIT:7:/usr/share/munin/VeraMono.ttf
--font AXIS:7:/usr/share/munin/VeraMono.ttf
-
--title), "Domain CPU usage", qw(
--base 1000
-r
--lower-limit 0
--vertical-label %
--height 600
--width 800
--units-exponent 0));

my $q = new CGI;

my $format = $q->param("format") || "png";
my $mime_type;
if (exists($formats{$format})) {
    $format =~ m|^(\w+)$| or die "Invalid format";
    $format = $1;
    $mime_type = $formats{$format};
} else {
    die "Invalid format";
}

push @args, "--imgformat", uc($format);

my $days = $q->param("days") || "8";
$days =~ m|^(\d+)$| or die "Invalid number of days specified";
$days = int($1);

my $type = $q->param("type") || "cpu";
$type =~ m|^(\w+)$| or die "Invalid graph type";
$type = $graph_types{$1} or die "Invalid graph type";

my $path = catfile(GRAPH_DIR, "*-$type-uuid_????????_????_????_????_????????????-?.rrd");
my @files = glob $path or die "No data found";

push @args, "--start", "-".$days."d";

my %uuids = map { m|(........_...._...._...._............)-.\.rrd$|; $1, 1 } @files;

# Color list shamelessly stolen from munin-graph
my @COLOUR = ("#22ff22", "#0022ff", "#ff0000", "#00aaaa", "#ff00ff",
              "#ffa500", "#cc0000", "#0000cc", "#0080C0", "#8080C0", "#FF0080",
              "#800080", "#688e23", "#408080", "#808000", "#000000", "#00FF00",
              "#0080FF", "#FF8000", "#800000", "#FB31FB");
my $color_index = 0;

foreach my $uuid (sort keys %uuids) {
  my @uuid_files = grep { m|$uuid-.\.rrd$| } @files;
  foreach my $i (0..$#uuid_files) {
    $uuid_files[$i] =~ m|^([^:]+)$|;
    push @args, "DEF:odata_${uuid}_$i=$1:42:AVERAGE";
    push @args, "CDEF:data_${uuid}_$i=odata_${uuid}_$i,UN,0,odata_${uuid}_$i,IF,10000,/";
  }
  push @args, "CDEF:total_${uuid}=0,".join(",+,", map {"data_${uuid}_$_"} 0..$#uuid_files).",+";
  push @args, "AREA:total_${uuid}".$COLOUR[($color_index++)%@COLOUR]."::STACK";
  # print STDERR "VM $uuid: @uuid_files\n";
}

$ENV{"PATH"} = "/usr/local/bin:/usr/bin:/bin";

print $q->header(-type=>$mime_type);
$|=1;

{
    use Data::Dumper;
    print STDERR "XVM usage: ", Dumper(\@args);
}
RRDs::graph (@args);