#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
cd "$DIR/.."

mapperUrl="localhost:5001/api/data/cloud"
count=0

while true; do
    statuscode=$(curl -s -o /dev/null -w "%{http_code}" $mapperUrl)

    if [ "$statuscode" == "200" ]; then
        response=$(curl -s $mapperUrl)

        if [ "$response" != "{}" ]; then
            break
        fi
    fi
    if [ $count == 0 ] || [ $count == 30 ]; then
        echo "Waiting data from device-mapper to start device-mqtt"
        count=0
    fi
    ((count++))
    sleep 10
done

export NODE_TLS_REJECT_UNAUTHORIZED='0'
mkdir -p "/etc/salicru/storage/mqtt" 
[ -f "/etc/salicru/storage/mqtt/measuresCache.json" ] || echo "{}" > "/etc/salicru/storage/mqtt/measuresCache.json"
[ -f "/etc/salicru/storage/mqtt/alarmsCache.json" ] || echo "{}" > "/etc/salicru/storage/mqtt/alarmsCache.json"
[ -f "/etc/salicru/storage/mqtt/pendingAlarms.json" ] || echo "[]" > "/etc/salicru/storage/mqtt/pendingAlarms.json"
[ -f "/etc/salicru/storage/mqtt/pendingMeasures.json" ] || echo "[]" > "/etc/salicru/storage/mqtt/pendingMeasures.json"
NODE_ENV=`cat /etc/salicru/env` node dist/index.js
