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

our ($gpath) = "/usr/local/opmon/libexec/pabx";
our ($opt_trunk,$opt_msg, $opt_help, $opt_host, $opt_user, $opt_password);
our ($dbfile);

sub main {
	my ($crit) = 0;
	my ($count) = 0;

	parse_args();

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

	`$gpath/exp/trunks.exp $opt_trunk $opt_host $opt_user $opt_password>/dev/null 2>&1`;
	$dbfile = "$gpath/exp/spool/trunks-$opt_trunk.log";

	file_age();

	open(FILE,"<$dbfile");
	while(<FILE>) {
		if (m/.*0+$opt_trunk\/\d+.*$/) {

			$count++;
			next if(/in-service\//);
			$crit = 1 if ($1 ne "in-service");
		}
	}
	close(FILE);

	if ($crit) {
		print "CRITICAL - $opt_msg\n";
		exit(2);
	}

	if ($count == 0) {
		print "UNKNOWN - $count itens com status 'in-service'\n";
		exit(3);
	}

	print "OK - $count itens com status 'in-service'\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,
           'm:s'   => \$opt_msg,              'msg:s'  => \$opt_msg,
           't:i'   => \$opt_trunk,            'trunk:i'  => \$opt_trunk,
	   'v'     => \$opt_help,             'help' => \$opt_help,
        );

	usage() if (!defined($opt_trunk) || defined($opt_help) || !defined($opt_msg));

}

sub usage {
	print "\tUsage:\t$0 -t <trunk number> -m '<critical message>' -h <host> -u <user> -p <password>\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;
