#!/usr/bin/perl -w

use strict;
use RRDs;

my $db = "/var/log/monitoring/loadavg/loadavg.rrd";
my $expires = 60;
my $host = "chocolate";
my $imageFormat = "PNG";
my $imageSuffix = "." . lc($imageFormat);
my $pageTitle = "Load Average";
my $service = "loadavg";
my $verticalLabel = "load average";

my %dataset = (
	'2' =>	{
		    'colour'	=>	'#ff0000',
		    'ds'	=>	'one',
		    'format'	=>	'%5.1lf',
		    'label'	=>	'One minute',
		    'style'	=>	'LINE2',
		},

	'1' =>	{
		    'colour'	=>	'#0000ff',
		    'ds'	=>	'five',
		    'format'	=>	'%5.1lf',
		    'label'	=>	'Five minute',
		    'style'	=>	'LINE2',
		},

	'0' =>	{
		    'colour'	=>	'#00ff00',
		    'ds'	=>	'fifteen',
		    'format'	=>	'%5.1lf',
		    'label'	=>	'Fifteen minute',
		    'style'	=>	'AREA',
		},
    );

my %graph = (
	'0' =>	{
		    'subtitle'	=>	'last 15 minutes',
		    'duration'	=>	'15m',
		    'file'	=>	'minute',
		},

	'1' =>	{
		    'subtitle'	=>	'last 90 minutes',
		    'duration'	=>	'90m',
		    'file'	=>	'hourly',
		},

	'2' =>	{
		    'subtitle'	=>	'last 36 hours',
		    'duration'	=>	'36h',
		    'file'	=>	'daily',
		},

	'3' =>	{
		    'subtitle'	=>	'last 10 days',
		    'duration'	=>	'10d',
		    'file'	=>	'weekly',
		},

	'4' =>	{
		    'subtitle'	=>	'last 5 weeks',
		    'duration'	=>	'5w',
		    'file'	=>	'monthly',
		},

	'5' =>	{
		    'subtitle'	=>	'last 78 weeks',
		    'duration'	=>	'78w',
		    'file'	=>	'yearly',
		},
    );

my $lastUpdate = RRDs::last $db;
my $rrd_error = RRDs::error;
die "Failed to obtain last update time from $db. $rrd_error\n" if $rrd_error;

my $now = time;
my $dateGMT = scalar gmtime($now);
my $dateLocal = scalar localtime($now);
my $lastGMT = scalar gmtime($lastUpdate);
my $lastLocal = scalar localtime($lastUpdate);
my $metaExpires = metaExpires($now + $expires);

print << "EOF";
Content-Type: text/html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>$host system monitoring - $pageTitle</TITLE>
<META HTTP-EQUIV="Refresh" CONTENT="$expires">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="$metaExpires">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
</HEAD>

<BODY BGCOLOR="#dddddd">

<CENTER>
<H1>$host system monitoring - $pageTitle</H1>
</CENTER>

<HR>

<P>
<TABLE>

    <TR>
	<TD>
	    Localtime is $dateLocal.
	</TD>

	<TD>
	    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
	</TD>

	<TD>
	    GMT time is $dateGMT GMT.
	</TD>
    </TR>

    <TR>
	<TD>
	    Statistics were last updated on $lastLocal. <BR>
	</TD>

	<TD>
	    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
	</TD>

	<TD>
	    Statistics were last updated on $lastGMT GMT.
	</TD>
    </TR>

</TABLE>
</P>

<HR>

EOF

my @comment;
my @def;
my @style;
my $maxlen = -1;

foreach my $ds (sort keys %dataset)
{
    my $len = length $dataset{$ds}{label};

    if ($len > $maxlen)
    {
	$maxlen = $len;
    }

    my $def = sprintf("%c", 97 + $ds);
    push @def, "DEF:${def}=${db}:$dataset{$ds}{ds}:AVERAGE";

    push
	@style,
	"$dataset{$ds}{style}:${def}$dataset{$ds}{colour}:$dataset{$ds}{label}";
}

$style[scalar @style - 1] .= "\\c";

foreach my $ds (sort keys %dataset)
{
    my $def = sprintf("%c", 97 + $ds);
    my $string = sprintf("%-${maxlen}.${maxlen}s", $dataset{$ds}{label});

    push
	@comment, "COMMENT:\\s";

    push
	@comment,
	"GPRINT:$def:MAX:Max $string $dataset{$ds}{format}    ";

    push
	@comment,
	"GPRINT:$def:MIN:Min $string $dataset{$ds}{format}    ";

    push
	@comment,
	"GPRINT:$def:AVERAGE:Avg $string $dataset{$ds}{format}    ";

    push
	@comment,
	"GPRINT:$def:LAST:Current $string $dataset{$ds}{format}\\s";
}

push @comment, "COMMENT:\\s";
push @comment, "COMMENT:\\s";
push @comment, "COMMENT:Graph last updated on $lastLocal  ";
push @comment, "COMMENT:                                  ";
push @comment, "COMMENT:Graph last updated on $lastGMT GMT";
push @comment, "COMMENT:\\c";

foreach (sort keys %graph)
{
    my ($avg, $xsize, $ysize) = graphit($_);
    my $rrd_error = RRDs::error;
    die "Failed to create $_ graph. $rrd_error\n" if $rrd_error;

    print join(" ", @$avg), "\n";
    print "\n<HR>\n";
}

print << "EOF";

</BODY>
</HTML>
EOF

###########################################################################

sub metaExpires
{
    my $time = shift;

    my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) =
	gmtime($time);

    my @days = ("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");

    my @months = (
	    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
	    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
	);

    $year += 1900;
    $hour = sprintf("%02d", $hour);
    $min = sprintf("%02d", $min);
    $sec = sprintf("%02d", $sec);

    return "$days[$wday], $mday $months[$mon] $year $hour:$min:$sec GMT";
}

sub graphit
{
    my $graph = shift;

    my $graphTitle = $graph{$graph}{subtitle};
    my $duration = $graph{$graph}{duration};
    my $file = $graph{$graph}{file};

    return RRDs::graph(
	    $host . "_" . $service . "_" . $file . $imageSuffix,
	    "--start", "now-$duration",
	    "--title", "$host $pageTitle - $graphTitle",
	    "--vertical-label", $verticalLabel,
	    "--width", 750,
	    "--height", 150,
	    "--rigid",
	    "--lower-limit", 0,
	    "--imgformat", $imageFormat,
	    "--imginfo",
		"<IMG SRC=\"%s\" WIDTH=\"%lu\" HEIGHT=\"%lu\" ALT=\"$file\">",
	    "--lazy",

	    "--color", "BACK#ffefdb",		# image background
	    "--color", "CANVAS#f5f5f5",		# graph background

	    @def,
	    @style,
	    @comment,
	);
}
