#!/usr/bin/env bash

while getopts "t:h:" Input;
do
    case ${Input} in
        t)          API_TOKEN=${OPTARG};;
        h)          HOST=${OPTARG};;
    esac
done

# Constants
BASE_URL="https://${HOST}/api/v2.0"


# Variable Initialisation
status=100 # default to 100 to force undefined if api requests fail
output_message=""
error_message=""

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

# Get current version
current_version=$(curl --silent -X GET -H "Authorization: Bearer ${API_TOKEN}" "${BASE_URL}/system/version" | jq -r)

# Get available Upate
available_update=$(curl --silent -X POST -H "Authorization: Bearer ${API_TOKEN}" "${BASE_URL}/update/check_available" | jq -r .status)

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

# parse output
if [ "${available_update}" == "UNAVAILABLE" ]; then
    status=0
    output_message="current Version: ${current_version}"

elif [ "${available_update}" == "AVAILABLE" ]; then

    # Get pending Updates
    pending_updates=$(curl -X POST -H "Authorization: Bearer ${API_TOKEN}" "${BASE_URL}/update/get_pending")

    status=2
    error_message="Updates available: ${pending_updates}"

elif [ "${available_update}" == "REBOOT_REQUIRED" ]; then
    status=2
    error_message="reboot required to apply update"

elif [ "${available_update}" == "HA_UNAVAILABLE" ]; then
    status=2
    error_message="HA unavailable"

fi

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

# Manage Output
case ${status} in

        0)
                echo "[OK]${output_message} | status=0"
                exit 0
                ;;
        1)
                echo "[WARNING]${error_message} | status=1"
                exit 1
                ;;
        2)
                echo "[ERROR]${error_message} | status=1"
                exit 2
                ;;
        *)
                echo "[UNKNOWN]Nicht definierte Augabe"
                exit 2
                ;;
esac
