#!/usr/bin/perl
use strict;
use Getopt::Long;

our ($gpath) = "/usr/local/opmon/libexec/pabx";
our ($dbfile) = "$gpath/exp/spool/load.log";
our ($exp_script) = "$gpath/exp/load.exp";
our ($opt_critical, $opt_warning, $opt_help, $opt_host, $opt_user, $opt_password );

sub main {
	my ($load);
	my ($found) = 0;

	parse_args();

	if (! -f "$gpath/exp/load.exp") {
		print "UNKNOWN - Por favor verifique a existencia dos arquivos expect\n";
		exit(3);
	}

	`$gpath/exp/load.exp $opt_host $opt_user $opt_password>/dev/null 2>&1`;

	file_age();

	open(FILE,"<$dbfile");
	while(<FILE>) {
		if (m/.*Cp:.*H\s+([\d\.]+)%.*Idl.*/) {
			$load = $1;
			$found = 1;
		}
	}
	close(FILE);


	if (!$found) {
		print "CRITICAL - Impossivel estimar utilizacao de CPU\n";
		exit(2);
	}

	if ($load > $opt_critical) {
		print "CRITICAL - Alarme Critical de utilizacao da CPU do PABX Avaya - SP $load\% |load=$load\%;$opt_warning;$opt_critical;0;100\n";
		exit(2);
	}

        if ($load > $opt_warning) {
                print "WARNING - Alarme Warning de utilizacao da CPU do PABX Avaya - SP $load\% |load=$load\%;$opt_warning;$opt_critical;0;100\n";
                exit(1);
        }

	print "OK - PABX CPU load $load\% |load=$load\%;$opt_warning;$opt_critical;0;100\n";
	exit(0);

}

sub parse_args {

	GetOptions(
           'h:s'   => \$opt_host,             'host:s' => \$opt_host,
           'u:s'   => \$opt_user,             'user:s' => \$opt_user,
           'p:s'   => \$opt_password,         'pwd:s' => \$opt_password,
           'w:i'   => \$opt_warning,          'warning:i'  => \$opt_warning,
           'c:i'   => \$opt_critical,         'critical:i' => \$opt_critical,
	   'v'     => \$opt_help,             'help' => \$opt_help,
        );

	usage() if (!defined($opt_warning) || !defined($opt_critical) || $opt_warning > $opt_critical || defined($opt_help) ||
                    !defined($opt_user) || !defined($opt_host) || !defined($opt_password));

}

sub usage {
	print "This plugin uses a Telnet connection to get Load of Avaya PABX\n";
	print "Usage:\t$0 -w <warning> -c <critical> -h <host> -u <user> -p <password>\n\t\tWith Warning <= Critical\n\n";
	exit(0);
}

sub file_age {
	my (@stats);
	my ($time) = time();
	my ($diff);

	@stats = stat($dbfile);
	$diff = $time - $stats[9];
	if ($diff >= 600) {
		print "CRITICAL - O arquivo $dbfile parece ser antigo\n";
		exit(2);
	}
}

&main;
