#!/bin/bash
#
# check_mi600
# Monitoring plugin to monitor a solar power inverter module.
# Supported modules:
# * Bosswerk Mi600
# * Huayu HY-600 
# * Huayu HY-800
#
# Copyright (c) 2022 Lars Vogdt <lars@linux-schulserver.de>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

CURL='/usr/bin/curl'
GREP='/usr/bin/grep'
AWK='/usr/bin/awk'
VERSION='0.2'
MAX_TRY=10

hostname='localhost'
user='admin'
pass='admin'

unset LANG

for exe in $CURL $AWK $GREP; do
    test -x "$exe" || { echo "Could not find or execute $exe. Please validate." >&2 ; exit 3; }
done

usage(){
    echo "Usage: $(basename $0) -H <host> -u <user> -p <password>"
    echo
    exit $1
}

print_version(){
    echo "$(basename $0) $VERSION"
    exit $1
}

get_webdata_now(){
    RES=$($CURL -s -u "$auth" "$hostname/status.html" | $GREP "webdata_now_p = " | $AWK -F '"' '{print $2}')
    echo "$RES"
}

while getopts H:u:p:hv OPTION ; do
    case "$OPTION" in
        h) usage 0
        ;;
        v) print_version 0
        ;;
        H) hostname="$OPTARG"
        ;;
        u) user="$OPTARG"
        ;;
        p) pass="$OPTARG"
        ;;
        *) echo "Unknown commandline option: $OPTION" >&2
           usage 3
        ;;
    esac
done

auth="$user:$pass"

ping -q -c3 $hostname >/dev/null 2>&1
if [ $? -eq 0 ]; then
    x=1
    RES=''
    while [[ $RES == '' ]] && [[ $x != $MAX_TRY ]]; do
        RES=$(get_webdata_now)
        let x=$x+1
        sleep 3
    done
    if [ "$RES" != '' ]; then
        if [ "$x" -lt 3 ]; then
            echo "Current power: $RES W | 'current_power'=$RES;;;;" 
            exit 0
        else
            echo "Current power: $RES W - retrieved only after $x tries | 'current_power'=$RES;;;;"
            exit 1
        fi
    else
        echo "Did not get a result after $MAX_TRY tries. Giving up"
        exit 2
    fi
else
    echo "Could not connect to host: $hostname"
    exit 2
fi
