#!/usr/bin/perl

use strict;

my $hostgroups_cfg = "/usr/local/nagios/etc/hostgroups.cfg";

my $name = '';
my %hostgroups;

open(FILE, "<$hostgroups_cfg");
while (<FILE>) {
    chomp;
    next if ($_ =~ /^[#;]/);
    $_ =~ s/[\r\n\s]+$//;
    $_ =~ s/^\s+//;
    next if ($_ eq ' ');

    if ($_ =~ /hostgroup_name\s+(.+)/i and !$name) {
        $name = $1;
    }
    elsif ($_ =~ /alias\s+(.+)/i and $name) {
        $hostgroups{$name} = $1;
        $name = '';
    }
}
close(FILE);

my $output = "document.write(\"";

foreach my $name (sort keys %hostgroups) {
    my $name_encoded = url_encode($name);
    $output .= "<tr><td width=40 align=right><img src=/nagios/images/greendot.gif width=13 height=14 name=status-$name></td><td nowrap><a href=/cgi-bin/nagios/status.cgi?hostgroup=$name_encoded&style=detail target=main onMouseOver=switchdot('status-$name',1) onMouseOut=switchdot('status-$name',0) class=NavBarItem>$hostgroups{$name}</a></td></tr>";
}

$output .= "\")";

print "Content-Type: text/html\n\n";
print $output;

sub url_encode
{
    my ($to_encode) = shift;

    $to_encode =~ s/([^a-zA-Z0-9_\-.])/uc sprintf("%%%02x",ord($1))/eg;
    $to_encode =~ s/\%2F/\//g;

    return $to_encode;
}
