#!/bin/bash

################################################################################
# @file		openems-mqtt-config
# @author	A. Pietsch <a.pietsch@onsolinno.de>
# @brief	Applies mender-configuration for openems mqtt-bridge
# @version	1.0.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.d/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

# generate uuid
UUID=$(cat /proc/sys/kernel/random/uuid)

# create folder and remove old configs
if [[ ! -d $MQTT_CONFIG_FOLDER ]]; then
    mkdir -p $MQTT_CONFIG_FOLDER
fi

# remove old config
ls ${MQTT_CONFIG_FOLDER} | grep .config
if [[ $? == 0 ]]; then
    echo "removing old config"
    rm ${MQTT_CONFIG_FOLDER}/*.config
fi

# generate mqtt.config
CONFIG_FILE="${MQTT_CONFIG_FOLDER}/${UUID}.config"
echo "generating $MQTT_CONFIG_FOLDER $CONFIG_FILE"

cat >${CONFIG_FILE} <<EOF
:org.apache.felix.configadmin.revision:=L"11"
alias=""
basepath=""
brokerUrl="${MQTT_BROKER_URL}"
cleanSessionFlag=B"true"
clientId="OpenEMS-1"
connection="Wss"
enabled=B"true"
id="MqttBridge"
ipBroker=""
keepAlive=I"60"
lastWillSet=B"false"
locale="Europe/Berlin"
mqttPriorities=[ \
  "URGENT", \
  "HIGH", \
  "LOW", \
  ]
mqttTypes=[ \
  "TELEMETRY", \
  "COMMAND", \
  "EVENT", \
  ]
password="${MQTT_PASS}"
payloadLastWill="Status\ :\ Connected"
portBroker=""
qosLastWill=I"0"
retainedFlag=B"true"
service.factoryPid="Bridge.Mqtt"
service.pid="Bridge.Mqtt.${UUID}"
timeStampEnabled=B"true"
topicLastWill="OpenEMS/Leaflet_0/Status/"
useCoreCycleTime=B"false"
username="${MQTT_USER}"
EOF
