#!/bin/bash
APCACCESS=/sbin/apcaccess
CAPACITY="$1"

MODEL=`$APCACCESS | grep -w MODEL | cut -d ":" -f 2 | sed s/^\ //g`
APCMODEL=`$APCACCESS | grep -w APCMODEL | cut -d ":" -f 2 | sed s/^\ //g`

if [ -z "$MODEL" ] && [ -z "$APCMODEL" ]
then
    MODEL="UNKNOWN"
elif [ -z "$MODEL" ] && [ ! -z "$APCMODEL" ]
then
    MODEL="$APCMODEL"
fi

LENGTH=$(( ${#MODEL} + 13 ))
LENGTHAPC=$(( ${#APCMODEL} + 13 ))

if [ "$LENGTH" -lt "$LENGTHAPC" ]
then
    LENGTH="$LENGTHAPC"
fi

LINE="--------------------------------------------------------------"
echo "${LINE:0:$LENGTH}"
echo "UPS model: $MODEL"

if [ ! -z "$APCMODEL" ]
then
    echo "APC model: $APCMODEL"
fi

echo "${LINE:0:$LENGTH}"
if [ -z "$CAPACITY" ]
then
    CAPACITY=`$APCACCESS | grep -w NOMPOWER | awk '{ print $3 }' `
    if [ -z "$CAPACITY" ]
    then
        for x in $MODEL $APCMODEL
        do
            STRING=`echo $x | grep -e [0-9] | sed 's/[A-Za-z]*//g'`
            if [ ! -z "$STRING" ]
            then
                CAPACITY=$(( ( $STRING * 60) / 100 ))
                break
            fi
        done
        if [ -z "$CAPACITY" ]
        then
            echo "Cannot determine capacity of UPS. Please specify:"
            echo "Syntax: $0 <watt>"
            echo "Example: $0 300"
            exit 1
        fi
    fi
fi

printf '%s %11s %s\n' 'Capacity:' "$CAPACITY" 'Watt'
PERCENT=`$APCACCESS |grep LOADPCT | awk '{ print $3 }' | cut -d "." -f 1`
echo $PERCENT | grep -e [0-9] >> /dev/null 2>&1
if [ "$?" == "0" ]
then
    printf '%s %15s %s\n' 'Load:' "$PERCENT" 'Percent'
    WATT=$(( $CAPACITY * $PERCENT / 100 ))
    printf '%s %14s %s\n' 'Usage:' "$WATT" 'Watt'
else
    printf '%s %15s %s\n' 'Load:' "0" 'Percent'
    printf '%s %14s %s\n' 'Usage:' "0" 'Watt'
fi
    
TIMELEFT=`$APCACCESS | grep TIMELEFT | awk '{ print $3 }' | cut -d "." -f 1` 
printf '%s %10s %s\n' 'Time left:' "$TIMELEFT" 'Minutes'
STATUS=`$APCACCESS | grep -w STATUS | awk '{ print $3 }'` 
if [ ! -z "$STATUS" ]
then
    printf '%s %13s %s\n' 'Status:' "$STATUS"
fi
echo "${LINE:0:$LENGTH}"
