#!/bin/sh

[ -z "$1" ] && exit

failed() {
  [ -f "$cloudApiConfig" ] && rm -f "$cloudApiConfig"
  [ -f "$cloudMqttConfig" ] && rm -f "$cloudMqttConfig"
  exit
}

ROOT=/www
CONFIG="$ROOT/config"
SCRIPT="$ROOT/script"

source $CONFIG/ap.conf
source $SCRIPT/utils/network.sh
source $SCRIPT/utils/token.sh
export CLOUD_ADDRESS="$1"

cloudApiConfig=`mktemp`
cloudMqttConfig=`mktemp`

mac=`getWanMac`
wget -vt 3 -T 5 --retry-connrefused $(getAuthHeader) -O "$cloudApiConfig" "$CLOUD_ADDRESS/api.conf?mac=$mac"
wget -vt 3 -T 5 --retry-connrefused $(getAuthHeader) -O "$cloudMqttConfig" "$CLOUD_ADDRESS/mqtt.conf?mac=$mac"

[ ! -s "$cloudApiConfig" ] && failed
[ ! -s "$cloudMqttConfig" ] && failed

cat $cloudApiConfig | grep CLOUD_ADDRESS | grep "$CLOUD_ADDRESS"
[ $? -ne 0 ] && failed

mv "$cloudApiConfig" "$CONFIG/api.conf"
mv "$cloudMqttConfig" "$CONFIG/mqtt.conf"

"$SCRIPT/update/update-ng-config.sh"
