#!/usr/bin/perl

# modified for iNET by Jonas Meurer 2012

use strict;
use Tie::File;
use lib qw(/usr/lib/nagios/plugins /usr/lib64/nagios/plugins /usr/local/nagios/libexec);
use utils qw(%ERRORS $TIMEOUT);
use Getopt::Long;
use vars qw($opt_I $opt_w $opt_c $opt_V $opt_h);

#my $TIMEOUT = 5;
#my %ERRORS=('OK'=>0,'WARNING'=>1,'CRITICAL'=>2,'UNKNOWN'=>3,'DEPENDENT'=>4);
my $PROGNAME = "Network Interface Errors";
our $file = "/proc/net/dev";

my $STATUS = "OK";

my @dataset;
my @splitinterface;
my $completestring;
my $countedoutput;
my $countedoutput_p;

my $if_rx_errors   = 0;
my $if_rx_dropped  = 0;
my $if_rx_overruns = 0;
my $if_rx_frame    = 0;
my $if_tx_errors   = 0;
my $if_tx_dropped  = 0;
my $if_tx_overruns = 0;
my $if_tx_carrier  = 0;
my $if_collisions  = 0;
my $if_error_count = 0;

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

if ($opt_I eq '') {
	print_help(); exit $ERRORS{"UNKNOWN"};
}
if ($opt_c eq '') {
	print_help(); exit $ERRORS{"UNKNOWN"};
}
if ($opt_w eq '') {
	print_help(); exit $ERRORS{"UNKNOWN"};
}

open(my $FH, $file) or die "$!\n";
while (<$FH>){
	$completestring = $_ if ($_=~ /$opt_I/);
	@splitinterface = split(/:\s*/,$completestring,2);
	@dataset = split(/\s+/,@splitinterface[1]);
	$if_rx_errors   = @dataset[2];
	$if_rx_dropped  = @dataset[3];
	$if_rx_overruns = @dataset[4];
	$if_rx_frame    = @dataset[5];
	$if_tx_errors   = @dataset[10];
	$if_tx_dropped  = @dataset[11];
	$if_tx_overruns = @dataset[12];
	$if_collisions  = @dataset[13];
	$if_tx_carrier  = @dataset[14];
}
close $FH;

$if_error_count = $if_rx_errors + $if_rx_overruns + $if_rx_frame + $if_tx_errors + $if_rx_overruns + $if_tx_carrier + $if_collisions;

if ($if_error_count >= $opt_w  && $countedoutput < $opt_c) {
	$STATUS = "WARNING";
}
elsif ($if_error_count >= $opt_c ) {
	$STATUS = "CRITICAL";
}
else {
	$STATUS = "OK";
}

printf("Network Interface $STATUS - $opt_I: RX: $if_rx_errors errors, $if_rx_dropped dropped, $if_rx_overruns overruns, $if_rx_frame frame - TX: $if_tx_errors errors, $if_tx_dropped dropped, $if_tx_overruns overruns, $if_tx_carrier carrier - Collisions: $if_collisions | RX_Errors=$if_rx_errors RX_Dropped=$if_rx_dropped RX_Overruns=$if_rx_overruns RX_Frame=$if_rx_frame TX_Errors=$if_tx_errors TX_Dropped=$if_tx_dropped TX_Overruns=$if_tx_overruns TX_Carrier=$if_tx_carrier Collisions=$if_collisions\n");
exit $ERRORS{"$STATUS"};

sub print_usage () {
	print "Usage: check_if_errors -I interface -c critical threshold -w warning threshold\n";
}

sub print_help () {
	print "$PROGNAME, Version: 1.01 \n";
	print "Copyright (c) 2012 Jonas Meurer, iNet\n\n";
	print_usage();
	print "
-I = interface
-c = critical threshold
-w = warning threshold\n";
}

