#!/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 175
--width 400
--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 $uuid = $q->param("uuid");
$uuid =~ m|^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$| or die "Invalid UUID specified";
$uuid = "$1_$2_$3_$4_$5";

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";

foreach my $i (0..$#files) {
  $files[$i] =~ m|^([^:]+)$|;
  push @args, "DEF:odata$i=$1:42:AVERAGE";
  push @args, "CDEF:data$i=odata$i,UN,0,odata$i,IF,10000,/";
}
push @args, "CDEF:total=0,".join(",+,", map {"data$_"} 0..$#files).",+";
push @args, "AREA:total#0000FF";

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