#!/bin/sh

[ -f /tmp/installing ] && exit 0
touch /tmp/installing
trap "rm -f /tmp/installing; exit" INT TERM EXIT

export REPO=https://openwrt.meganet.com.vn
export FW_VERSION=18.06.8

if [ -z "$CLOUD" ] ; then
  [ ! -f /www/config/api.conf ] && echo "no api.conf" && exit 0
  source /www/config/api.conf
fi
[ -z "$CLOUD" ] && echo "no CLOUD" && exit 0

[ -z "$dist" ] && dist=releases
[ -z "$version" ] && version=latest
target=`cat /etc/openwrt_release  | grep DISTRIB_TARGET | cut -d "'" -f 2`
arch=`cat /etc/openwrt_release  | grep DISTRIB_ARCH | cut -d "'" -f 2`

export codeUrl="$REPO/$dist/$version.tgz"
versionUrl="$REPO/$dist/version"
installerUrl="$REPO/scripts/install.sh"

upgradeUrl() {
  echo "$REPO/$FW_VERSION/targets/$target/$1-$CLOUD-sysupgrade.bin"
}

upgrade() {
  sysupgrade -n `upgradeUrl $1` &
  echo "upgrading"
  echo "upgrading" > /tmp/installing
  exit 0
}

upgrade501() {
  url=`upgradeUrl ens202ext`
  cat > /tmp/sysupgrade.sh <<- EOM
wget -vT 5 -O /tmp/sysupgrade.bin "$url"
dd if=/tmp/sysupgrade.bin of=/tmp/kernel.bin bs=64 count=24576
dd if=/tmp/sysupgrade.bin of=/tmp/rootfs.bin bs=64 count=193536 skip=24576
mtd -e kernel write /tmp/kernel.bin kernel
mtd -r -e rootfs write /tmp/rootfs.bin rootfs
EOM

  sh -x /tmp/sysupgrade.sh &
  echo "upgrading"
  echo "upgrading" > /tmp/installing
  exit 0
}

upgradeOldYuncore() {
  url=`upgradeUrl $1`
  cat > /tmp/sysupgrade.sh <<- EOM
wget -vT 5 -O /tmp/sysupgrade.bin "$url"
fw_setenv bootcmd "bootm 0x9fe80000 || bootm 0x9f050000"
mtd -e firmware -r write /tmp/sysupgrade.bin firmware
EOM

  sh -x /tmp/sysupgrade.sh &
  echo "upgrading"
  echo "upgrading" > /tmp/installing
  exit 0
}

update() {
  export codeUrl="$codeUrl"
  wget -q -O /tmp/installer.sh "$installerUrl"
  if [ -s /tmp/installer.sh ] ; then
    echo "updating"
    echo "updating" > /tmp/installing
    sh -x /tmp/installer.sh >/tmp/install.log 2>&1 &
  fi
  exit 0
}

latestVersion=`wget -qO- $versionUrl`
`grep $FW_VERSION /etc/openwrt_release &>/dev/null` && upgraded=1 || upgraded=0
`grep $latestVersion /www/version &>/dev/null` && updated=1 || updated=0
if [ "$upgraded" == 1 ] ; then
  if [ "$updated" == 1 ] ; then
    echo "up to date"
    exit 0
  else
    update
  fi
fi

model=`/www/script/model.sh`
case "$model" in
  xd3200|\
  xd6700)
    upgrade $model
    ;;
  ens202|\
  501)
    upgrade501
    ;;
  701)
    upgradeOldYuncore xd3200
    ;;
  305)
    upgradeOldYuncore xd6700
    ;;
  *)
    echo "$model is not supported"
    update
esac
