#!/usr/bin/perl -w
#
# Generate some RSS from Nagios status file.
#
# Ian Chard  3/6/2005
#
# $Id: nagrss.pl,v 1.2 2005/08/17 11:16:32 chardi Exp $

use strict;

use XML::RSS;
use DateTime::Format::W3CDTF;
use Data::Dumper;

my $STATUS_DAT="/usr/local/nagios/var/status.dat";
my $NAGIOS_BASE_URL="http://network.sers.ox.ac.uk/nagios";

my @services;
my $i=0;
my $ignoring=1;


open STATUS, $STATUS_DAT or die $!;
while(<STATUS>)
{
	chop;

	if(/^host {$/ || /^service {$/)
	{
		$ignoring=0;
		next;
	}
	elsif(!$ignoring && /^	}$/)
	{
		$ignoring=1;
		$i++;
	}
	elsif(!$ignoring)
	{
		my @line=split /[	=]/;
		$services[$i]{$line[1]}=$line[2];
	}
}
close STATUS;


my $rss=new XML::RSS(version=>1.0);

$rss->add_module(prefix=>"ss", uri=>"http://purl.org/rss/1.0/modules/servicestatus/");

$rss->channel(
	title		=>	"SERS system status",
	link		=>	"http://www.sers.ox.ac.uk"
	);

foreach my $service (@services)
{
	my ($title, $link, $lastok);

	if(exists $$service{"service_description"})
	{
		$title=$$service{"host_name"}.':'.$$service{"service_description"};
		$link="$NAGIOS_BASE_URL/cgi-bin/extinfo.cgi?type=2&host=".$$service{"host_name"}."&service=".$$service{"service_description"};
		$link=~s/ /%20/g;
		$lastok=$$service{"last_time_ok"};
	}
	else
	{
		$title=$$service{"host_name"};
		$link="$NAGIOS_BASE_URL/cgi-bin/extinfo.cgi?type=1&host=".$$service{"host_name"};
		$link=~s/ /%20/g;
		$lastok=$$service{"last_time_up"};
	}

	my $dtf=DateTime::Format::W3CDTF->new;

	$rss->add_item(
		title		=>	$title,
		link		=>	$link,
		ss => {
			responding	=>	$$service{"current_state"}==0? "true":"false",
			lastChecked	=>	$dtf->format_datetime(DateTime->from_epoch(epoch=>$$service{"last_hard_state_change"})),
			lastSeen	=>	$dtf->format_datetime(DateTime->from_epoch(epoch=>$lastok)),
			availability	=>	"",
			averageResponseTime=>	""
			}
		);
}
print $rss->as_string;
