#!/usr/bin/perl -w

#
# Copyright (C) 2007 Francesc Guasch
#
# 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 2
# of the License, or (at your option) any later version.
#
# 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
#

use strict;
use Getopt::Long;

my $VERSION = "0.03";

use lib '/usr/local/nagios/plugins';
use utils qw(%ERRORS &print_revision &support &usage);

my ($PASSWORD,$WARNING	,$CRITICAL	,$TIMEOUT,$DEBUG) 
	= (''	,15		,5			,20);
my $CMD_MOPUPS 	= "/opt/mopups/bin/mopups";
my $HOST		= "localhost";
{
	my $me = $0;
	$me =~ s#.*/##;

	my ($version,$help);
	GetOptions(
		debug 			=> \$DEBUG,
		version			=> \$VERSION,
		help 			=> \$help,
		'timeout=s'		=> \$TIMEOUT,
		'warning=s' 	=> \$WARNING,
		'critical=s' 	=> \$CRITICAL,
		'password=s'	=> \$PASSWORD,
		'mopups=s'		=> \$CMD_MOPUPS,
		'host=s'		=> \$HOST,
	);
	if ($help) {
		print "$me [--debug] [--version] [--help]"
				." [--password=\"\"]"
				." [--mopups=$CMD_MOPUPS]"
				." [--host=$HOST]"
				." [--warning=1] [--critical=0]\n";
		exit();
	}
	if ($version) {
		print_revision($me,$VERSION);
		print "$me v$VERSION\n";
		exit;
	}
}

$SIG{'ALRM'} = sub {
        print ("ERROR: No response from UPS (alarm)\n");
        exit $ERRORS{"UNKNOWN"};
};
alarm($TIMEOUT);


my $RET = 'UNKNOWN';

my $MOPUPS;
my $cmd ="echo \"exit\" | $CMD_MOPUPS -P \"$PASSWORD\" $HOST";
#warn $cmd;
open $MOPUPS,"$cmd|" or do {
	$RET = 'UNKNOWN';
	print "$RET: $!\n";
	exit $ERRORS{$RET};
};

my @info;
while (<$MOPUPS>) {
	next unless /\w/;
	chomp;
	if (/Invalid password/) {
		push @info,$_;
		$RET='UNKNOWN';
		last;
	}
	if (/Battery Status/) {
		if (/Good/) {
			$RET = 'OK';
		} else {
			$RET = 'WARNING' unless $RET eq 'CRITICAL';
		}
	} elsif (/Battery Charge.*?/) {
		my ($charge) = /(\d+)/;
		unless ($charge =~ /^[\d+.]/) {
			$RET = 'UNKNOWN';
		} else {
			$RET = 'WARNING' if $charge < $WARNING && $RET ne 'CRITICAL';
			$RET = 'CRITICAL' if $charge < $CRITICAL;
		}
	}
	s/\s\s+/ /;
	print "$_\n" if $DEBUG;
	push @info,$_ unless /^(==|Host)/;
}
close $MOPUPS;

print "$RET: ".(join " , ",@info)."\n";
exit($ERRORS{$RET});
