#!/usr/bin/env python3

'''Use Mender Config json input and generate OpenEMS MQTT Brdige Config'''

import json
import os.path
import sys
import chevron


if len(sys.argv) != 2:
    print("Must be invoked with exactly one argument: The JSON configuration.")
    sys.exit(1)

config=sys.argv[1]
DEST_CONF="/data/openems.d/Bridge/Mqtt/9bff9faa-4b8c-44cd-aabf-c0d552904ec2.config"
TEMP_FILE="/usr/lib/mender-configure/templates/openems-mqtt-config.mustache"

if not os.path.exists(config):
    print(f"Error: {config} does not exist.")
    sys.exit(1)

try:
    with open(config) as input_params:
        data = json.load(input_params)
        if "MQTT_BROKER_URL" in data and "MQTT_USER" in data and "MQTT_PASS" in data:
            with open(TEMP_FILE, 'r') as template_file:
                DIR_PATH = "/data/openems.d/Bridge/Mqtt/"
                if not os.path.exists(DIR_PATH):
                    os.makedirs(DIR_PATH)
                with open(DEST_CONF, "w") as config_file:
                    config_file.write(chevron.render(template_file, data))
                config_file.close()
                print("Config file created/updated.")
        else:
            print("MQTT Data missing, skip.")
except json.JSONDecodeError as exception:
    print(f"Failed to parse the configuration JSON, error: {exception}")
    sys.exit(1)
except Exception as exception: # pylint: disable=broad-except
    print(f"Failed with unhandled error: {exception}")
    sys.exit(1)
