#!/bin/sh

[ -z "$ROOT" ] && ROOT=/www
CONFIG=$ROOT/config
SCRIPT=$ROOT/script

[ -f $CONFIG/ng.conf ] && source $CONFIG/ng.conf
source $CONFIG/ap.conf
source $CONFIG/api.conf
source $SCRIPT/utils/token.sh
source $SCRIPT/utils/network.sh
source $SCRIPT/utils/misc.sh

[ -z "$1" ] && sleep 2

failed() {
  local reason=`encodeURIComponent "$1"`
  wget -T 5 -qO /dev/null $(getAuthHeader) "$CLOUD_ADDRESS/failed?type=config&reason=$reason"
}

success() {
  wget -T 5 -qO /dev/null $(getAuthHeader) "$CLOUD_ADDRESS/success?type=config"
}

echo "Updating ng config..."
configFile=`mktemp`

wget -vt 3 -T 5 $(getAuthHeader) -O "$configFile" "$CLOUD_ADDRESS/ng.conf"
[ $? -ne 0 ] && echo "  failed" >&2 && exit 1

if [ -s "$configFile" ] ; then
  validConfig=`cat $configFile | grep HASH_CONFIG_SITE`
  if [ ! -z "$validConfig" ] ; then
    curConf=`mktemp`
    cat /www/config/ng.conf | grep -v DEBUG > $curConf
    curConfHash=`md5 $curConf`
    newConfHash=`md5 $configFile`
    rm -f $curConf
    if [ "$curConfHash" != "$newConfHash" ] ; then
      echo "  applying new config"
      mv "$configFile" $CONFIG/ng.conf
      apply=true
      success
    else
      echo "  config is up-to-date"
    fi
  else
    failed "invalid"
    echo "  config is invalid"
  fi
else
  echo "  config is up-to-date"
fi
rm -f "$configFile"

echo "Updating mqtt config..."
mac=`getWanMac`
wget -qt 3 -T 5 $(getAuthHeader) -O "$configFile" "$CLOUD_ADDRESS/mqtt.conf?mac=$mac"
[ $? -ne 0 ] && echo "  failed" >&2 && exit 1

if [ -s "$configFile" ] ; then
  validConfig=`cat $configFile | grep bishbosh_connect_username`
  if [ $? -eq 0 ] ; then
    hashMqttOld=`md5 /www/config/mqtt.conf`
    hashMqttNew=`md5 "$configFile"`
    if [ "$hashMqttOld" != "$hashMqttNew" ] ; then
      mv "$configFile" $CONFIG/mqtt.conf
      /etc/init.d/ng_ap2 restart job
    fi
  else
    echo "  mqtt config is invalid"
  fi
fi
rm -f "$configFile"

# Get new template before apply config
$SCRIPT/update/update-template.sh

[ "$apply" ] && $SCRIPT/update/apply-config.sh

exit 0
