#!/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 $alert_type;
my ($state, $host, $servicedesc, $output, $author, $ackcomment, $now, $contact, $title, $guid, $url_params);

# This decides whether it is a host or a service problem
if ($ENV{NAGIOS_SERVICEDESC}) {
	$alert_type = "service";
} else {
	$alert_type = "host";
}

$now           = $ENV{NAGIOS_TIMET};
$contact       = $ENV{NAGIOS_CONTACTNAME};
$contact =~ s%/.*%%;	# Remove any / in the contactname

# Get data according to type
if ($alert_type eq "service") {
	$state		= $ENV{NAGIOS_SERVICESTATE};
	$host		= $ENV{NAGIOS_HOSTNAME};
	$servicedesc	= $ENV{NAGIOS_SERVICEDESC};
	$output 	= $q->escapeHTML($ENV{NAGIOS_SERVICEOUTPUT});
	$author		= $ENV{NAGIOS_SERVICEACKAUTHOR};
	$ackcomment	= $q->escapeHTML($ENV{NAGIOS_SERVICEACKCOMMENT});
	$title		= "$host $servicedesc";
	$url_params	= "type=2&host=$host&service=$servicedesc";
	$guid		= "/nagios/$host/$servicedesc/".$now,
} else {
	$state		= $ENV{NAGIOS_HOSTSTATE};
	$host		= $ENV{NAGIOS_HOSTNAME};
	$output		= $q->escapeHTML($ENV{NAGIOS_HOSTOUTPUT});
	$author		= $ENV{NAGIOS_HOSTACKAUTHOR};
	$ackcomment	= $q->escapeHTML($ENV{NAGIOS_HOSTACKCOMMENT});
	$title		= "$host";
	$url_params	= "type=1&host=$host";
	$guid		= "/nagios/$host/".$now,
}

if ($ENV{NAGIOS_NOTIFICATIONTYPE} eq "ACKNOWLEDGEMENT") {
	$state = "ACKNOWLEDGEMENT";
}

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: $title",
	link => "${Settings::server}${Settings::extinfo}?$url_params",
	pubDate => rfc822($now),
	guid => $guid,
	mode => "insert",
	# dc => {creator => $author || "unassigned"},	# This line doesn't work for RSS 2.0
	);

my $desc = "Output: $output";
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));
}
