#!/usr/bin/env perl

# Check current power consumption of a "Yello Stromzaehler"
# Author: Daniel Berlin <mail@daniel-berlin.de>
# Version 0.1

use strict;
use warnings;

use File::Basename;
use Getopt::Long;

use vars qw(
    $opt_host
    $opt_warning
    $opt_critical
    $opt_help
    $opt_usage
    $opt_version
);

my $progname = basename($0);

my %ERRORS = (
    'OK'       => '0',
    'WARNING'  => '1',
    'CRITICAL' => '2',
    'UNKNOWN'  => '3',
);

##### Handle command line input ####################################################################

Getopt::Long::Configure('bundling');
GetOptions(
    "H=s" => \$opt_host,
    "w=s" => \$opt_warning,	"warning=s"  => \$opt_warning,
    "c=s" => \$opt_critical,	"critical=s" => \$opt_critical,
    "h"   => \$opt_help,	"help"       => \$opt_help
) || die "Try $progname --help for more information.\n";

sub print_help() {
    print "$progname - Check current power consumption.\n";
    print "Options:\n";
    print "  -H                    Host or IP address\n";
    print "  -c, --critical        Warning  threshold (watt)\n";
    print "  -w, --warning         Critical threshold (watt)\n";
    print "  -h, --help            Display this help and exit\n";
}

unless(     $opt_host
    and     $opt_warning
    and     $opt_warning  =~ /^\d+$/
    and     $opt_critical
    and     $opt_critical =~ /^\d+$/
    and not $opt_help
) {
    print_help();
    exit $ERRORS{'UNKNOWN'};
}

##### Perform check ################################################################################

my @output = qx|/usr/bin/curl -q -s curl -s http://$opt_host/index.html 2>/dev/null|;
   @output = grep(/\<div class="akt_leistung"\>/, @output);

unless(@output eq 1) {
    print "UNKNOWN - unable to determine current power consumption\n";
    exit $ERRORS{'UNKNOWN'};
}
unless($output[0] =~ m|>(\d+) W<|) {
    print "UNKNOWN - unable to extract current power consumption\n";
    exit $ERRORS{'UNKNOWN'};
}

my $watt  = $1;
my $state = "OK";

if($opt_warning && $opt_critical) {
    if($watt >= $opt_warning ) { $state = "WARNING";  }
    if($watt >= $opt_critical) { $state = "CRITICAL"; }

    print "$state - current power consumption: ${watt} watt |";
    print " watt=${watt};${opt_warning};${opt_critical}\n";
    exit $ERRORS{$state};
}
else {
    print_usage();
    exit $ERRORS{'UNKNOWN'};
}

####################################################################################################
