#!/bin/sh

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

source $CONFIG/api.conf
source $SCRIPT/utils/misc.sh
source $SCRIPT/utils/token.sh

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

clean() {
  cd /tmp
  rm -rf "$codeDir"
}

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

failed() {
  clean

  echo "failed $1"
  local reason=`encodeURIComponent "$1"`

  wget -T 5 -qO /dev/null $(getAuthHeader) "$CLOUD_ADDRESS/failed?type=code&reason=$reason"
  exit
}

echo "Update code"
echo -n "  Checking for code update... "

# download code
version=`cat "$ROOT/version" 2>/dev/null`
checksum=`cat /etc/code_checksum 2>/dev/null`
wget -T 5 -qO code.tgz $(getAuthHeader) "$CLOUD_ADDRESS/code/download?version=${version}&checksum=${checksum}"
[ ! -s code.tgz ] && echo "up-to-date" && clean && exit
echo "found"

echo -n "  Verifing checksum... "
checksum=`md5 code.tgz`
wget -T 5 -qO /dev/null $(getAuthHeader) "$CLOUD_ADDRESS/code/verify?algo=md5&checksum=$checksum"
[ $? -ne 0 ] && failed "checksum"
echo "matched"

echo -n "  Extracting... "
tar -zxf code.tgz
[ "$?" -ne 0 ] && failed "extract"
echo "done"

rm -rf code.tgz
rm -rf config
cp -rf $CONFIG .
chmod -R +x script

if [ -s script/update/post-update.sh ] ; then
  ROOT="$codeDir" sh script/update/post-update.sh
  [ "$?" -ne 0 ] && failed "post update"
fi

/etc/init.d/cron stop
kill -9 "`ps | grep monitor | grep -v grep | awk '{print $1}'`" 2>/dev/null
touch /tmp/installing

sleep 30

# copy code
echo "  Moving files..."
cp script/ng_ap2 /etc/init.d
cd /
rm -rf /www
mv "$codeDir" /www
cat /www/version > /etc/code_version
echo "$checksum" > /etc/code_checksum

echo "  Updating config..."
sh /www/install.sh

success
