#!/usr/bin/perl -w
#
# Check Cisco DSL SNR Margin
#

use strict;
use Getopt::Std;

my $snmp_get = "/usr/bin/snmpget";
my $snr_oid = ".1.3.6.1.2.1.10.94.1.1.3.1.4.9";

use vars qw($opt_v $opt_h $opt_H $opt_C $opt_w $opt_c);
my(%ERRORS) = ( OK=>0, WARNING=>1, CRITICAL=>2, UNKNOWN=>3, WARN=>1, CRIT=>2 );
my($message, $status);
my (@ignore);

sub print_usage () {
        print "Usage: \n\tcheck_cisco_dsl [-v] [-h] -H host -C community -w low_snr_warn -c low_snr_crit\n\n";
}

sub print_help () {
        print <<HELP;

                Check Cisco DSL SNR Margin version 1.0
                Copyright 2010 Zachary McGibbon
                zachary.mcgibbon\@gmail.com

HELP

        print_usage();
}

# return true if parameter is not in ignore list
sub valid($) {
        my($v) = $_[0];
        $v = lc $v;
        foreach ( @ignore ) { return 0 if((lc $_) eq $v); }
        return 1;
}

sub check_snr {
        my($C) = shift;
        my($H) = shift;
        my($w) = shift;
        my($c) = shift;

        my $snmp_cmd = "${snmp_get} -v1 -Ovq";
        my $community = $opt_C;
        my $host = $opt_H;

        my $snr = `${snmp_cmd} -c ${community} ${host} ${snr_oid}`;

        chomp($snr);

        if($snr <= $w) {
                $status = $ERRORS{WARN};
        }
        if($snr <= $c) {
                $status = $ERRORS{CRIT};
        }

        $message = "$snr dB";
}

$ENV{'BASH_ENV'}='';
$ENV{'ENV'}='';

our($opt_H, $opt_C, $opt_w, $opt_c, $opt_v, $opt_h);

getopts("H:C:w:c:v:h");

my @vars = ($opt_H, $opt_C, $opt_w, $opt_c);

if ($opt_h) {print_help(); exit $ERRORS{'OK'};}

foreach ( @vars ) {
        unless($_) {
                print_help();
                exit $ERRORS{WARNING};
        }
}

$status = $ERRORS{OK}; $message = '';

if(($opt_w <= 0) && ($opt_c <= 0)) {
        print "SNR must be above 0\n\n";
        print_help(); exit $ERRORS{'WARN'};
}

check_snr($opt_C,$opt_H,$opt_w,$opt_c);

if( $message ) {
        if( $status == $ERRORS{OK} ) {
                print "OK: ";
        } elsif( $status == $ERRORS{WARNING} ) {
                print "WARNING: ";
        } elsif( $status == $ERRORS{CRITICAL} ) {
                print "CRITICAL: ";
        }
        print "$message\n";
}

exit $status;