#!/usr/bin/perl

use XML::RSS;
use DateTime;
use Nagios::Plugin::Getopt;

#my $nbMaxItem = 30;
#my $filename = "/var/www/html/rss/nagios.rss";
my $dt = DateTime->now->set_time_zone('Europe/Paris');

$ng = Nagios::Plugin::Getopt->new(
	usage => "%s [-m maximum_items] [-f RSS_file] -n notification_type -h host [-s service] -e state -o output",
	version => '1.0'
);

$ng->arg(
	spec => 'maxitem|m=i',
	help => q(Maximum number of item),
	required => 0,
	default => 30
);
$ng->arg(
	spec => 'file|f=s',
	help => q(Path to RSS file),
	required => 0,
	default => "/var/www/html/rss/nagios.rss"
);
$ng->arg(
	spec => 'notification_type|n=s',
	help => q(Notification type),
	required => 1
);
$ng->arg(
	spec => 'host|H=s',
	help => q(Host name),
	required => 1
);
$ng->arg(
	spec => 'service|s=s',
	help => q(Service description),
	required => 0,
	default => "_NONE_"
);
$ng->arg(
	spec => 'state|e=s',
	help => q(State),
	required => 1
);
$ng->arg(
	spec => 'output|o=s',
	help => 'Nagios Ouput',
	required => 0
);

$ng->getopts();

my $localhost = `hostname`;
#my $notif = $ARGV[0];
#my $host = $ARGV[1];
#my $service = $ARGV[2];
#my $output = $ARGV[4];
#my $state = $ARGV[3];
my $notif = $ng->notification_type;
my $host = $ng->host;
my $service = $ng->service;
my $output = $ng->output;
my $state = $ng->state;
my $filename = $ng->file;
my $nbMaxItem = $ng->maxitem;

my $type;

if($service ne "_NONE_"){
	$type = 2;
} else {
	$type = 1;
}

my $service_url = $service;
$service_url =~ tr/ /+/;
my $host_url = $host;
$host_url =~ tr/ /+/;

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

if(!(-e $filename)){
	# Le fichier n'existe pas
        # On le crée
        my $date_sz = $dt->strftime("%a, %d %b %Y %H:%M:%S %z");
        $rss->channel(
                title => $localhost,
                link => "http://$localhost/nagios/cgi-bin/status.cgi?host=all",
                language => 'fr',
                description => 'Récapitulatif des changements d\'états des services supervisés par le Nagios',
                pubDate => $date_sz
        );
} else {
	# Le fichier existe déjà

	# On l'ouvre
	$rss->parsefile($filename);
}

# On vire les vieilles entrées si plus de nbMaxItem
while(@{$rss->{'items'}} >= $nbMaxItem){
	pop(@{$rss->{'items'}});
}
# On le met à jour
my $title = "[".$dt->strftime("%d %b %Y %H:%M:%S")."] $notif: $host";
my $url = "http://$localhost/nagios/cgi-bin/extinfo.cgi?type=$type&host=$host_url";
if( $service ne "_NONE_"){
	$title .= "/$service";
	$url .= "&service=".$service_url;
}
$title .= " is $state";

$rss->add_item(
	title => $title,
	link => $url,
	mode => 'insert',
	description => "$output",
	pubDate => $dt->strftime("%a, %d %b %Y %H:%M:%S %z")
);
$rss->channel(lastBuildDate => $dt->strftime("%a, %d %b %Y %H:%M:%S %z"));

# On ecrit le fichier
$rss->save($filename);

