#!/bin/bash

################################################################################
# @file		openems-mqtt-config
# @author	A. Pietsch <a.pietsch@onsolinno.de>
# @brief	Applies mender-configuration for openems mqtt-bridge
# @version	1.1.0
# @date		07.03.2023
# 
# @copyright GPLv3 (c) 2023 A. Pietsch <a.pietsch@onsolinno.de>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
################################################################################



if [ $# -ne 1 ]; then
    echo "Must be invoked with exactly one argument: The JSON configuration." 1>&2
    exit 2
fi

CONFIG="$1"

MQTT_CONFIG_FOLDER="/data/openems/Bridge/Mqtt"

if ! [ -e "$CONFIG" ]; then
    echo "Error: $CONFIG does not exist." 1>&2
    exit 0
fi

# get MQTT Data
MQTT_BROKER_URL="$(jq -r -e .MQTT_BROKER_URL <"$CONFIG")"
MQTT_PASS="$(jq -r -e .MQTT_PASS <"$CONFIG")"
MQTT_USER="$(jq -r -e .MQTT_USER <"$CONFIG")"

# verify MQTT Data
if [[ "$MQTT_BROKER_URL" == "null" ]]; then
    echo "MQTT_BROKER_URL not found"
    exit 0
fi

if [[ "$MQTT_PASS" == "null" ]]; then
    echo "MQTT_PASS not found"
    exit 0
fi

if [[ "$MQTT_USER" == "null" ]]; then
    echo "MQTT_USER not found"
    exit 0
fi

# Set Config (ToDo: update config if exists)
echo "creating Openems Config MqttBridge"

curl -X POST -H 'Authorization: Basic QWRtaW46YWRtaW4=' \
     -H 'Content-Type: application/json' \
     -d '{"jsonrpc":"2.0","method":"createComponentConfig","params":{
      "factoryPid": Bridge.Mqtt,
      "properties": [{
        "name": "id",
        "value": "MqttBridge"
      },{
        "name": "brokerUrl",
        "value": "'${MQTT_BROKER_URL}'"
      },{
        "name": "password",
        "value": "'${MQTT_PASS}'"
      },{
        "name": "username",
        "value": "'${MQTT_USER}'"
      }
    ]}}' \
    http://localhost:8086/jsonrpc
