#!/usr/bin/perl
use strict;
use POSIX qw(strftime);
use XML::RSS;
use CGI;

{ package Settings; do "/etc/nagios/rss.cfg" }

my $q = new CGI;

my $state         = $ENV{NAGIOS_SERVICESTATE};
if ($ENV{NAGIOS_NOTIFICATIONTYPE} eq "ACKNOWLEDGEMENT") {
	$state = "ACKNOWLEDGEMENT";
}
my $host          = $ENV{NAGIOS_HOSTNAME};
my $servicedesc   = $ENV{NAGIOS_SERVICEDESC};
my $serviceoutput = $q->escapeHTML($ENV{NAGIOS_SERVICEOUTPUT});
my $author        = $ENV{NAGIOS_SERVICEACKAUTHOR};
my $ackcomment    = $q->escapeHTML($ENV{NAGIOS_SERVICEACKCOMMENT});
my $now           = $ENV{NAGIOS_TIMET};
my $contact       = $ENV{NAGIOS_CONTACTNAME};
$contact =~ s%/.*%%;	# Remove any / in the contactname

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

$rss->channel(title => $Settings::title,
	link => $Settings::server,
	language => "en",
	description => $Settings::description,
	);

my @items = ();

my $rssfile = "${Settings::rssdir}/$contact.rss";

if (-e $rssfile) {
	my $old = new XML::RSS;
	$old->parsefile($rssfile);
	@items = @{$old->{'items'}};
	@items = splice @items, 0, $Settings::max - 1;
	$rss->{'items'} = \@items;
}

my %attributes = ( title => "$state: $host $servicedesc",
	link => "${Settings::server}${Settings::extinfo}?type=2&host=$host&service=$servicedesc",
	pubDate => rfc822($now),
	guid => "/nagios/$host/$servicedesc/".$now,
	mode => "insert",
	# dc => {creator => $author || "unassigned"},	# This line doesn't work for RSS 2.0
	);

my $desc = "Output: $serviceoutput";
if ($author) {
	$desc .= "\n\nAcknowledged by: $author\nComment: $ackcomment";
}

$attributes{description} = $desc;

$rss->add_item( %attributes );

$rss->save($rssfile);

sub rfc822 {
	return strftime("%a, %d %b %Y %H:%M:%S %z", localtime(shift));
}
