#!/bin/bash

# @Name:    openems-telemetry-configs
# @Author:  s.bauer@consolinno.de
# @Content: Processes telemetry configs for the consolinno cloud.
#           The configuration leads to a new OpenEMS Telemetry Component which sends telemetry data for a given
#           device on the plant to the consolinno cloud, using a pre-existing "mqttBridge".

set -e

STATE="$1"
FOLDER="$2"/files
MENDER_INVENTORY_LIST=/data/leaflet/Inventory.list

adjustInventory() {
    if [ ! -f $MENDER_INVENTORY_LIST ]; then
        echoerr "Warning, mender inventory file $MENDER_INVENTORY_LIST not found"

        return
    fi

    echoerr "Adjusting mender inventory for device $DEVICE_NAME..."

    echo -e "\ntelemetry_device_name=$DEVICE_NAME" >>$MENDER_INVENTORY_LIST
    echo "telemetry_device_type=$DEVICE_TYPE" >>$MENDER_INVENTORY_LIST
}

# see mender docs, regular logging should use stderr stream - this is a redirection
# TODO test
echoerr() {
    echo "$@" 1>&2
}

# ============== here we go ===============

case "$STATE" in

NeedsArtifactReboot)
    echo "No"
    ;;

SupportsRollback)
    echo "No"
    ;;

ArtifactInstall)
    echo "Processing OpenEMS Telemetry Configs..."

    if [ ! -d "$FOLDER" ]; then
        echo "Directory $FOLDER not found, aborting"
        exit 1
    else
        files=($FOLDER/*)
        JSON_FILE=${files[0]}

        echo "Working with payload file $JSON_FILE"
    fi

    # get MQTT Data
    DEVICE_TYPE="$(jq -r .device_type <"$JSON_FILE")"
    DEVICE_NAME="$(jq -r .device_name <"$JSON_FILE")"
    DATA_SOURCE_COMPONENT="$(jq -r .data_source_component <"$JSON_FILE")"
    PAYLOADS="$(jq -r .payloads <"$JSON_FILE")"

    # verify MQTT Data
    # status quo: DEVICE_TYPE gets ignored for the openems components, but included in the mender inventory

    if [[ "$DEVICE_NAME" == "null" ]]; then
        echo "DEVICE_NAME not found"
        exit 1
    fi

    if [[ "$DATA_SOURCE_COMPONENT" == "null" ]]; then
        echo "DATA_SOURCE_COMPONENT not found"
        exit 1
    fi

    if [[ "$PAYLOADS" == "null" ]]; then
        echo "PAYLOADS not found"
        exit 1
    fi

    echo "Creating OpenEMS TelemetryComponent"

    curl -s -X POST -H 'Authorization: Basic QWRtaW46YWRtaW4=' \
        -H 'Content-Type: application/json' \
        -d '{"jsonrpc":"2.0","method":"createComponentConfig","params":{
            "factoryPid": MqttTelemetryComponent,
            "properties": [
            {
                "name": "id",
                "value": "mqttTelemetryComponent-'${DEVICE_NAME}'"
            },
            {
                "name": "otherComponentId",
                "value": "'${DATA_SOURCE_COMPONENT}'"
            },
            {
                "name": "mqttBridgeId",
                "value": "mqttBridgeConsolinnoCloud"
            },
            {
                "name": "mqttId",
                "value": "'${DEVICE_NAME}'"
            },
            {
                "name": "payloads",
                "value": '"${PAYLOADS}"'
            },
            {
                "name": "subscriptionList",
                "value": [
                    "LOW!control/'${DEVICE_NAME}'/setPower!1!true!true!1!1"
                ]
            },
            {
                "name": "publishList",
                "value": [
                    "LOW!telemetry/'${DEVICE_NAME}'!0!true!true!0!2"
                ]
            },
            {
                "name": "configurationDone",
                "value": "true"
            },
            {
                "name": "createdByOsgi",
                "value": "true"
            }
            ]}}' \
        http://localhost:8086/jsonrpc

        adjustInventory
    ;;
esac
