#!/usr/bin/env python3

# -*- mode: Python; encoding: utf-8; indent-offset: 4; autowrap: nil -*-

# (c) Michael Honkoop <mhonkoop@comsolve.nl>

# License: GNU General Public License v2

# in combination with a rule for "individual program call instead of agent" as described on the official docs of CheckMK:
# https://docs.checkmk.com/latest/en/datasource_programs.html
#
# The commandline to be used in CheckMK is : this_script_name.py $HOSTADDRESS$

import sys
import json
import requests

def main():
    args = sys.argv[1:]
    if len(args) < 1:
        print("Usage: script.py IP or FQDN")
        sys.exit(1)

    address = args[0]
    try:
        response = requests.get('http://{}/api/v1/data'.format(address))
    except requests.exceptions.RequestException as e:
        raise SystemExit(e)

    parsed = response.json()
    print('<<<local>>>')
    iterate_json(parsed)

# Using For Loop to iterate thru the data offered by the P1-API
# Threshold values are tuned to my own setup, they might need ajustment for others.

def iterate_json(json_obj):
    for key, value in json_obj.items():
        if isinstance(value, dict):
            iterate_json(value)
        else:
            if key.startswith("active"):
                if key.endswith("_w"):
                    print(f"P {key} Power={value};2100;2200;2300;0;2500 Current Watts:{value}")
                if key.endswith("_v"):
                    print(f"P {key} volt={value};252;253;260;0;300 Current Volts:{value}")
                if key.endswith("_a"):
                    print(f"P {key} amps={value};8;10;15;0;20 Current Amps:{value}")
                if key.endswith("tariff"):
                    print(f"P {key} tariff={value};;;;; Current Tariff:{value}")

# Additional information is available, but not at current needed
#            if key.startswith("external"):
#                continue
#            else:
#                print(f"0 {key} - {value}")

if __name__ == "__main__":
    main()