#!/bin/bash

#local settings
local_host=127.0.0.1
local_port=1883
local_topic="application/+/device/+/event/up"


#remote server settings
remote_host="8861485d8ab74c78a37a971104adff6f.s1.eu.hivemq.cloud"
remote_port="8883"
remote_username="hivemq.webclient.1723312330268"
remote_password="e8YkEU3:7zT6Na#d&?Qn"
remote_topic="powertechmeterdata"

#remote_cafile="/path/to/ca_certificates/ca.crt"  # Ca
#remote_certfile="/path/to/client_certificates/client.crt"  # crt
#remote_keyfile="/path/to/client_certificates/client.key"  # key

PERSISTENT_FILE="/usr/local/failed_messages.txt"

resent_data()
{
if [[ -s $PERSISTENT_FILE ]]; then
    while IFS= read -r failed_message; do
        mosquitto_pub -h "$remote_host" -p "$remote_port"  -u "$remote_username" -P "$remote_password" -t "$remote_topic" -m "$failed_message" --insecure --property "publish" "message-expiry-interval" 259200
        if [[ $(echo $?) -ne 0 ]]; then
            return
        fi
        escaped_message=$(printf '%s\n' "$failed_message" | sed 's/[\/&]/\\&/g')
        sed -i "/$escaped_message/d" "$PERSISTENT_FILE"
    done < "$PERSISTENT_FILE"
    #truncate -s 0 "$PERSISTENT_FILE"
fi
}
publish_data()
{
    local message_publish=$1
    #Forward all up to remote server.
    #mosquitto_pub -h "$remote_host" -p "$remote_port" --cafile "$remote_cafile" --certfile "$remote_certfile" --keyfile "$remote_keyfile" -u "$remote_username" -P "$remote_password" -t "$remote_topic" -m "$message"
    mosquitto_pub -h "$remote_host" -p "$remote_port"  -u "$remote_username" -P "$remote_password" -t "$remote_topic" -m "$message_publish" --insecure --property "publish" "message-expiry-interval" 259200
    if [[ $(echo $?) -ne 0 ]]; then
        echo -n "$message_publish" >> "$PERSISTENT_FILE"
    else
        resent_data
    fi

}

#Subscribe to all local up messages
mosquitto_sub -h "$local_host" -p "$local_port" -t "$local_topic" | while read message; do
message_address=$(echo "$message" | jq -r '.deviceInfo.devEui')
message_object=$(echo "$message" | jq -c '.object')
message_date=$(echo "$message" | jq -r '.time')
message_fcnt=$(echo "$message" | jq -r '.fCnt')
message_fport=$(echo "$message" | jq -r '.fPort')
message=$(cat <<EOF
{ "DevEUI": "$message_address", "data": $message_object, "time": "$message_date", "fcnt": "$message_fcnt", "fport": "$message_fport" }
EOF
    )
publish_data "$message"

done

