#!/usr/bin/perl
###########################################################################
#
#          FILE:  check_dlan_connection
#
#         USAGE:  check_dlan_connection [opts] [debug]
#                 --help                  : show help message
#                 --host <dlanIP>         : dlan IP address
#                 --device <check device> : dlan device name
#                 --router <dlan router>  : dlan router name
#                 --warntx <int>          : set TX warn level
#                 --crittx <int>          : set TX critical level
#                 --warnrx <int>          : set RX warn level
#                 --critrx <int>          : set RX critical level
#                 debug       Create a tracefile for remote debugging
#
#        AUTHOR:  Tobias D. Oestreicher
#
#       LICENSE:  GPLv3 <http://www.gnu.org/licenses/gpl.txt>
#       VERSION:  0.1
#       CREATED:  03.11.2015
#
###########################################################################
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, see <http://www.gnu.org/licenses/>.
#
###########################################################################

use strict;
use warnings;
use LWP::Simple;
use JSON;
use Data::Dumper;
use Getopt::Long;


##########################################################################
#      D O    N O T    E D I T    B E L O W    T H I S    L I N E
##########################################################################

# init vars
my $warntx = "";
my $warnrx = "";
my $crittx = "";
my $critrx = "";
my $dev = "";
my $router = "";
my $ip = "";
my $help = 0;


##########################################################################
sub print_unknown
##########################################################################
  {
    print "UNKNOWN: Cannot connect to host ".$ip."\n";
    exit 3;
  }


##########################################################################
sub get_dlan_txrx_at_router
##########################################################################
  {
    my ($ip,$dev,$router) = @_;
    my ($dev_mac,$dev_name,$dev_type,$dev_fw) = get_devinfo_from_name ($ip,$dev);
    my ($router_mac,$router_name,$router_type,$router_fw) = get_devinfo_from_name ($ip,$router);
    if ( $dev_mac eq "" ) { print "UNKNOWN: device ".$dev." not known\n";exit 3; } 
    if ( $router_mac eq "" ) { print "UNKNOWN: router ".$router." not known\n";exit 3; } 
    my $devcontent = get("http://".$ip.":22879/?version=1&target=HomePlug&key=Remote.Device{MacAddress=".$router_mac."}") or print_unknown;
    my $devdecoded = decode_json($devcontent);
    my @RouterView = @{ $devdecoded->{'result'}{'Device'}{'DataRates'}  };
    foreach my $routerdev ( @RouterView ) {
      if ( $routerdev->{'MacAddress'} eq $dev_mac ) {
        return ($dev_name, $dev_type, $router_name, $routerdev->{'TxRate'}, $routerdev->{'RxRate'},$dev_fw);
      }
    }


  }


##########################################################################
sub get_devinfo_from_name
##########################################################################
  { 
    my ($ip,$dev) = @_;
    my ($dev_mac,$dev_name,$dev_type,$dev_fw) = "";

    my $content = get('http://'.$ip.':22879/?version=1&target=HomePlug&key=Remote')
        or print_unknown;
    my $decoded = decode_json($content);
    my @RemoteDevices = @{ $decoded->{'result'}{'Remote'}{'Device'} };
    foreach my $remdev ( @RemoteDevices ) {
      if ( $remdev->{'Config'}->{'UserString'} eq $dev ) {
        $dev_mac = $remdev->{'MacAddress'};
        $dev_fw = $remdev->{'FriendlyFirmwareVersion'};
        $dev_name = $remdev->{'Config'}->{'UserString'};
        $dev_type = $remdev->{'Config'}->{'DeviceName'};
      }  
    }
    if ( $dev_mac eq "" ) {
      my $localcontent = get('http://'.$ip.':22879/?version=1&target=HomePlug&key=Local') or print_unknown;
      my $localdecoded = decode_json($localcontent);
      if ( $dev eq $localdecoded->{'result'}{'Local'}{'Device'}{'Config'}{'UserString'} ) {
        $dev_mac = $localdecoded->{'result'}{'Local'}{'Device'}{'MacAddress'};
        $dev_fw = $localdecoded->{'result'}{'Local'}{'Device'}{'FriendlyFirmwareVersion'};
        $dev_name = $localdecoded->{'result'}{'Local'}{'Device'}{'Config'}{'UserString'};
        $dev_type = $localdecoded->{'result'}{'Local'}{'Device'}{'Config'}{'DeviceName'};
      }
    }
    
    return ($dev_mac,$dev_name,$dev_type,$dev_fw);
  }


##########################################################################
sub help_msg
##########################################################################
  {
    print "check_dlan_connection v. 0.1 - Nagios Check for dLAN - (c) Tobias D. Oestreicher\n";
    print "--------------------------------------------------------------------------------\n";
    print "Usage:\n";
    print "  check_dlan_ext [options]\n";
    print "\n";
    print "Options:\n";
    print "  --help                      : show this help msg\n";
    print "  --host <dLan IP>            : ip adress of a dlan wifi device\n";
    print "  --device <device-name>      : name of dlen device to check \n";
    print "  --router <router-name>      : dlan router/endpoint name\n";
    print "  --warntx <tx-warn>          : tx warn level\n";
    print "  --crittx <tx-crit>          : tx crit level\n";
    print "  --warnrx <rx-warn>          : rx warn level\n";
    print "  --critrx <rx-crit>          : rx crit level\n";
    print "  debug                       : creating tracefile for debug\n";
    print "\n";
    print "Example:\n";
    print "  check_dlan_ext --host 192.168.178.9 --device dlan-wz --router dlan-buero \\\n";
    print "                 --warntx 80 --crittx 60 --warnrx 80 --critrx 60\n";
    print "--------------------------------------------------------------------------------\n";
    print "\n";
    exit;
  }


##########################################################################
##########################################################################
#
#                                 M A I N
#
##########################################################################
##########################################################################

# process sysargs
GetOptions ("host=s" => \$ip,
            "device=s" => \$dev, # numeric
            "router=s" => \$router, # string
            "warntx=i" => \$warntx, # string
            "crittx=i" => \$crittx, # string
            "warnrx=i" => \$warnrx, # string
            "critrx=i" => \$critrx, # string
            "help" => \$help) # flag
    or help_msg();

if ( $help eq 1 || $dev eq "" || $router eq "" || $ip eq "" || $warntx eq "" || $crittx eq "" || $warnrx eq "" || $critrx eq "" ) { help_msg(); }

# gather informations
my ($dev_name, $dev_type, $router_name, $tx, $rx, $dev_fw) = get_dlan_txrx_at_router($ip,$dev,$router);


# check thresholds
my $RETTXT="OK: ";
my $RETCODE=0;

if ( $tx <= $warntx ) {
  $RETTXT="WARNING: ";
  $RETCODE=1;
}

if ( $rx <= $warnrx) {
  $RETTXT="WARNING: ";
  $RETCODE=1;
}

if ( $tx <= $crittx ) {
  $RETTXT="CRITICAL: ";
  $RETCODE=2;
}

if ( $tx <= $critrx ) {
  $RETTXT="CRITICAL: ";
  $RETCODE=2;
}

# final output
print $RETTXT."dlan device \"".$dev_name."\" has connection (TX:".$tx."/RX:".$rx.") | rx=".$rx." tx=".$tx."\n";
print "dlan-device name: ".$dev_name."\ndevice type: ".$dev_type."\nconnected to: ".$router_name."\n"; 

exit $RETCODE;

##########################################################################
#                                 E N D
##########################################################################









