#!/bin/sh

failed() {
  echo "failed: $1"
  cd /tmp
  rm -rf $codeDir
  exit 0
}

syncTime() {
  echo "ICT-7" > /tmp/TZ
  local serverTime=`wget -T 5 --no-check-certificate -qO - "https://$CLOUD/cloud/api/time"`
  if [ ! -z "$serverTime" ] ; then
    serverTime=`echo "$serverTime" | sed 's/T/ /g' | cut -c0-19`
    date -u -s "$serverTime"
  fi
  echo $serverTime
}

[ -z "$codeUrl" ] && failed "no codeUrl"
[ -z "$CLOUD" ] && source /www/config/api.conf 2>/dev/null
[ -z "$CLOUD" ] && failed "no cloud address"
[ -z "`syncTime`" ] && failed "sync time"

codeDir=`mktemp -d` && cd "$codeDir"

echo "Downloading..."
wget -T 5 -qO code.tgz "$codeUrl"
[ ! -s code.tgz ] && failed "download"

hash=`md5sum code.tgz | awk '{print $1}'`

echo "Extracting..."
tar zxvf code.tgz
[ $? -ne 0 ] && failed "extract"
rm code.tgz
[ ! -s install.sh ] && failed "no install.sh"
[ ! -d bish-bosh ] && failed "no bish-bosh"
[ ! -d script ] && failed "no script"

chmod -R +x script/*
chmod +x install.sh

export ROOT=$codeDir
CONFIG="$ROOT/config"
SCRIPT="$ROOT/script"

skip=true sh -x $SCRIPT/init.sh
source "$CONFIG/ap.conf"
source "$SCRIPT/utils/network.sh"
source "$SCRIPT/utils/token.sh"

echo "Getting config..."
configAddr="https://$CLOUD/cloud/api/config"

mac=`getWanMac`
wget -T 5 -qt 3 --retry-connrefused $(getAuthHeader) -O "$CONFIG/api.conf" "$configAddr/api.conf?mac=$mac"
wget -T 5 -qt 3 --retry-connrefused $(getAuthHeader) -O "$CONFIG/mqtt.conf" "$configAddr/mqtt.conf?mac=$mac"

[ ! -s "$CONFIG/api.conf" ] && failed "api.conf"
[ ! -s "$CONFIG/mqtt.conf" ] && failed "mqtt.conf"

rm -rf /www
mkdir -p /www

echo "Moving files..."
rm -rf wget-log*
mv -f * /www

cd /www
rm -rf "$codeDir"

echo "$hash" > /etc/code_checksum
cat /www/version > /etc/code_version

echo "Installing..."
sh /www/install.sh
