#!/usr/bin/perl
use strict;
use warnings;
use HTML::TagCloud;

# License: GPL v2 (and not above)
# Generate basic tagclouds of Nagios host outages, service outages and
# service warnings.

# Note: This script is intentionally simple and commits the sin of
#       mixing code and HTML. This is because both are simple in this
#       case and it's much easier to deploy this way. for the record, I
#       know this is bad and I ignored it on purpose.

my (%warnings, %criticals, %outages);

################## Configs ############################

my $outpath = '/var/www/';
my $now     = localtime;
my $cutoff  = (time - 2_592_000); # now (epoch) minus 30 days (in seconds)
my $nagios  = 'http://my.example.org/nagios/cgi-bin/status.cgi?host=';

################## Configs ############################

# $app /var/log/nagios/archives/nagios-*.log /var/log/nagios/nagios.log

while(<>) {
  next if /CHECK_NRPE/;
  if (m/\[(\d+)\] SERVICE ALERT: \S+?;(.+?);WARNING;HARD/) {
    $warnings{$2}++ unless ($1 < $cutoff);
  }
  if (m/\[(\d+)\] SERVICE ALERT: \S+?;(.+?);CRITICAL;HARD/) {
    $criticals{$2}++ unless ($1 < $cutoff);
  }
  if (m/\[(\d+)\] HOST ALERT: (\S+);DOWN;HARD/) {
    $outages{$2}++ unless ($1 < $cutoff);
  }
}

my %loglines = (
                 warnings  => \%warnings,
                 criticals => \%criticals,
                 outages   => \%outages
               );

########################## Print the output ##########################

print <<EOCSS;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <title>Nagios Clouds - generated $now</title>
    <style type="text/css">

a {
 text-decoration: none;
 font-family: Verdana, Arial, Helvetica, sans-serif;
 color: #0000FF;
}

a:hover {
 background: #CCCCFF;
}

#htmltagcloud {
 text-align:  center;
 background: #eee;
}
span {
 padding: 0 12px;
}

EOCSS

my $cloudcount =  0;
my $fontsize   = 12;

while ($cloudcount < 25) {
  print "span.tagcloud$cloudcount { font-size: ${fontsize}px;}\n";
  print "span.tagcloud$cloudcount a {text-decoration: none;}\n";

  $cloudcount++;
  $fontsize ++;
}

print <<EOHEAD;

    </style>
  </head>
  <body>
    <h1 style="text-align: center;">Nagios Clouds</h1>
    <h3 style="text-align: center;">Generated $now</h3>

EOHEAD

foreach my $heading (keys %loglines) {
  my $cloud = HTML::TagCloud->new;

  # Link only works to hosts
  my $nagios_type = $loglines{$heading};
  print uc qq!<h2 style="text-align: center;">$heading</h2>!;
  print "<br />";
  foreach my $key (keys %$nagios_type) {
    $cloud->add("$key($nagios_type->{$key})", "$nagios$key", $nagios_type->{$key});
  }
  print $cloud->html(70);
}

print <<EOF;

  <p style="text-align: center;">
  </p>
  </body>
</html>
EOF

exit 0;

