#!/usr/bin/perl

use strict;
use Getopt::Long;
use vars qw($opt_V $opt_h $opt_P $opt_H $opt_w $opt_c $PROGNAME);
use lib "/usr/local/nagios/libexec"  ;
use utils qw(%ERRORS &print_revision &support &usage);

my $remote_user = "root";
my $path_to_ssh = "/usr/bin/ssh";
my $path_to_grep = "/usr/bin/grep";
my $path_to_awk = "/usr/bin/awk";
my $warn = 50000;
my $crit = 60000;

$PROGNAME = "check_pfstate";
$ENV{'PATH'}='';
$ENV{'BASH_ENV'}='';
$ENV{'ENV'}='';

Getopt::Long::Configure('bundling');
GetOptions
        ("V"   => \$opt_V, "version"    => \$opt_V,
         "h"   => \$opt_h, "help"       => \$opt_h,
         "H=s" => \$opt_H, "hostname=s" => \$opt_H,
	 "w=s" => \$opt_w, "warning=s"	=> \$opt_w,
	 "c=s" => \$opt_c, "critical=s"	=> \$opt_c);

if ($opt_V) {
        print_revision($PROGNAME,'$Revision: 1112 $');
        exit $ERRORS{'OK'};
}
if ($opt_h) {
	print_help();
	exit $ERRORS{'OK'};
}
if ($opt_w) {
	if ($opt_w =~ /(\d+)/) {
		$warn = $1;
	} else {
		usage("Invalid values: $opt_w\n");
		exit $ERRORS{'OK'};
	}
}
if ($opt_c) {
	if ($opt_c =~ /(\d+)/) {
		$crit = $1;
	} else {
		usage("Invalid values: $opt_c\n");
		exit $ERRORS{'OK'};
	}
}
($opt_H) || usage("Host name/address not specified\n");
my $host = $1 if ($opt_H =~ /([-.A-Za-z0-9]+)/);
($host) || usage("Invalid host: $opt_H\n");

my $result = `$path_to_ssh -l $remote_user $host '/sbin/pfctl -s info' | $path_to_grep entries`;
chomp $result;
$result =~ /(\d+)/;
$result = $1;

print "$result PF state entries\n";

exit $ERRORS{'CRITICAL'} if ($result >= $crit);
exit $ERRORS{'WARNING'} if ($result >= $warn);
exit $ERRORS{'OK'};


sub print_help {
        print_revision($PROGNAME,'$Revision: 1112 $');
        print "Copyright (c) 2002 Jason Dixon\n\nThis plugin checks the number of state table entries on a PF-enabled OpenBSD system.\n\n";
        print "Usage:\t-H, --hostname=<HOST> [-w, --warning=<WARNING>] [-c, --critical=<CRITICAL>]\n\n\tDefault warning is 50000 and critical is 60000.\n\n";
        support();
}

