#!/usr/bin/perl
#
#
# apcaccess.pl Thu 1/1/2009 7:37 PM
#
# John Liebl <liebl@thetethered.com>
#
# Script for apcupsd apcaccess output.
#
# Usage: apcaccess.pl [option]
#
# Valid command line options are:
#
# Load, Battery, and Time
#
# Each of which will extract the corresponding data from the log file.
# One and only one option can be used at a time.
#
######################################################################

# Change line to a 1 to debug.
$debug=0;

$arg = $ARGV[0];

# Default location
$_ = `c:\\apcupsd\\bin\\apcaccess.exe`;

print "$_\n" if $debug;

################################################

# Will be used to compute uptime.
# Output of STARTTIME format "Thu Jan 01 13:54:57 Eastern Standard Time 2009"
/STARTTIME:\s(.+)/;
print "StartTime = $1\n" if $debug;
$stime=$1;

# Upime not completed yet
$Uptime=0;

/MODEL\s+:\s(.+)/;
print "Model = $1\n" if $debug;
$Model=$1;

/LOADPCT\s+:\s+(\d{1,3}.\d)/;
print "UPS Load = $1\n" if $debug;
$load=$1;

/BCHARGE\s+:\s+(\d{1,3}.\d)/;
print "Battery Charge = $1\n" if $debug;
$charge=$1;

/BATTV\s+:\s+(\d{1,3}.\d)/;
print "Battery Voltage = $1\n" if $debug;
$battery=$1;

/LINEV\s+:\s+(\d{1,3}.\d)/;
print "Line Voltage = $1\n" if $debug;
$line=$1;

/TIMELEFT\s+:\s+(\d{1,3}.\d)/;
print "Time Left = $1\n" if $debug;
$time=$1;

/CUMONBATT:\s+(\d+)/;
print "Time on battery = $1\n" if $debug;
$onbattery=$1;

################################################

# Let's check command line ...
if ( $arg =~ /^-?Load$/i ) {
    $Input  = $load;
    $Output = $charge;
}
elsif ( $arg =~ /^-?Time$/i ) {
    $Input  = $time;
    $Output = 0;
}		
elsif ( $arg =~ /^-?Onbatt$/i ) {		
    $Input = $onbattery;
    $Output = 0;
}
elsif ( $arg =~ /^-?Voltage$/i ) {
    $Input  = $battery;
    $Output = $line;
}
else {
    print "\nInvalid option specified on command line.\n";
    &usage;
    exit 0;
}
################################################

print "\n Debug Input: $Input, Output: $Output\n" if $debug;

# Output to MRTG
print " $Input\n $Output\n $Uptime\n $Model\n";

sub usage {
    print "\nValid options are: Load, Voltage, Onbatt, and Time,\n";
}

#--- eof apcaccess.pl