#!/usr/bin/perl
# TICKET: ---
# AUTHOR: Otavio Honorio 
# ORGANIZATION: OpServices
# VERSION: 1.0
# CREATED: 15/07/2015
# REVISION: ---
# AUTHOR REVISION: --- 

use strict;
use warnings;
use vars qw ($np); # Global Variables
use Nagios::Plugin;
use Params::Validate qw(:all); # Used for check parameters of param of the functions

sub get::opts {
	# Constructor
	$np = Nagios::Plugin->new(
		shortname => "OPMON LATENCY",
		license => "Developed by OpServices\nAuthor:\nOtavio Honorio - otavio.honorio\@opservices.com.br",
		blurb => "Description:\nChecking for latency of hosts and services.",
		url => "www.opservices.com.br/suporte",
		version => "1.0",
		extra => "\nBased:\nhttp://search.cpan.org/dist/Nagios-Plugin/lib/Nagios/Plugin.pm\nhttp://nagiosplug.sourceforge.net/developer-guidelines.html",
		usage => "Usage: %s [-?|-h] | [ -c|--critical=<threshold> ] [ -w|--warning=<threshold> ]",
	);

	# add valid command line options and build them into your usage/help documentation.
	$np->add_arg(spec => "warning|w=s", required => 1, default => 50, help => ["Exit with WARNING value if less or higher than PERCENT, Example (-w 5) is higher than 5 or (-w 5:) is less than 5"]);
	$np->add_arg(spec => "critical|c=s", required => 1, default => 100, help => ["Exit with CRITICAL value if less or higher than PERCENT, Example (-w 10) is higher than 10 or (-w 10:) is less than 10"]);
	
	# Parse @ARGV and process standard arguments (e.g. usage, help, version)
	$np->getopts;
}

sub main {
	# Execute constructor of parameters configured
	get::opts();

	my @out = `/usr/local/opmon/bin/opmonstats -m -d AVGACTSVCLAT,AVGACTHSTLAT -c /usr/local/opmon/etc/opmon.cfg`
		or $np->nagios_exit(return_code => "UNKNOWN", message => "Error in command execution 'opmonstats'");

	chomp(@out);
	if (scalar(@out) == 0) {
		$np->nagios_exit(return_code => "CRITICAL", message => "No result from command 'opmonstats'");
	}

	my $svc = $out[0]/1000;
	my $hst = $out[1]/1000;

	my $output = "Latency - Host: ".$hst."s / Service: ".$svc."s";

	# Perfdata output format i.e. label=value[uom];[warn];[crit];[min];[max]
	$np->add_perfdata(label => 'service_latency', value => $svc, warning => $np->opts->warning, critical => $np->opts->critical, uom => 's', min => 0);
	$np->add_perfdata(label => 'host_latency', value => $hst, warning => $np->opts->warning, critical => $np->opts->critical, uom => 's', min => 0);

	my $code = undef;

	if ($np->check_threshold($hst) or $np->check_threshold($svc) == 2) {
		$code = 2;
	} elsif ($np->check_threshold($hst) or $np->check_threshold($svc) == 1) {
		$code = 1;
	} else {
		$code = 0;
	}

	# Exit with return code
	$np->nagios_exit(return_code => $code, message => $output);
}

&main;
