#!/usr/bin/perl
##########################################################################
# nagios_plugin_wrapper
#
# Executes the given nagios plugin and produces an XML with data for pandora
# to be used as agent plugin. This allows to have DATA based on the errorlevel
# and use the descriptive information on description for the module
#
# Usage: nagios_plugin_wrapper <module_name> <nagios plugin execution with its parameters>
##########################################################################
# Copyright (c) 2010 Artica Soluciones Tecnologicas S.L
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
##########################################################################

use strict;
use warnings;

my $command = "";
my @opts = @ARGV;
my $module_name = shift(@opts);
$command = join(' ', @opts);

if ($command ne ""){
    my $module_data = `$command`;
    my $module_description = $module_data;
    my $ReturnCode = ($? >> 8) & 0xff;


    # Get the errorlevel if is a Nagios plugin type (parsing the errorlevel)
    # Nagios errorlevels: 	
    #('OK'=>0,'WARNING'=>1,'CRITICAL'=>2,'UNKNOWN'=>3,'DEPENDENT'=>4);

    # By default is unknown
    $module_data = "";

    if ($ReturnCode == 2){
	    $module_data = 0;
    } 
    elsif ($ReturnCode == 3){
	    $module_data = ''; # not defined = Uknown 
    } 
    elsif ($ReturnCode == 0){
	    $module_data = 1; 
    } 
    elsif ($ReturnCode == 1){
	    $module_data = 2;  # need to be managed on module thresholds
    } 
    elsif ($ReturnCode == 4){
	    $module_data = 3; # need to be managed on module thresholds
    }

    print "<module>";
    print "<name>".$module_name."</name>\n";
    print "<type>generic_proc</type>\n";
    print "<data>".$module_data."</data>\n";
    print "<description><![CDATA[" . $module_description . "]]></description>\n";
    print "</module>\n";

}