#!/bin/sh
export REPO=https://openwrt.meganet.com.vn
export FW_VERSION=18.06.4

[ -z "$dist" ] && dist=alpha
versionUrl="$REPO/$dist/version"
installerUrl="$REPO/scripts/install.sh"

prepareUpgradeNew() {
  url="$REPO/$FW_VERSION/targets/ar71xx/generic/xd6700-vinmart-sysupgrade.bin"
  cat > /etc/sysupgrade.conf <<- EOM
## This file contains files and directories that should
## be preserved during an upgrade.

/etc/opkg/
/etc/opkg.conf
/etc/config/
/etc/crontabs/root
/etc/persistent/
/www/config/
EOM

  cat > /tmp/sysupgrade.sh <<- EOM
  wget --no-check-certificate -vT 5 -O /tmp/sysupgrade.bin "$url"
  sysupgrade /tmp/sysupgrade.bin
EOM
}

prepareUpgradeOld() {
  url="$REPO/$FW_VERSION/targets/ar71xx/generic/xd6700-vinmart-sysupgrade.bin"
  cat > /tmp/sysupgrade.sh <<- EOM
  wget --no-check-certificate -vT 5 -O /tmp/sysupgrade.bin "$url"
  fw_setenv bootcmd "bootm 0x9fe80000 || bootm 0x9f050000"
  mtd -e firmware -r write /tmp/sysupgrade.bin firmware
EOM
}

upgrade() {
  `grep 12.09 /etc/openwrt_release &>/dev/null` && prepareUpgradeOld || prepareUpgradeNew

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

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

  export codeUrl="$REPO/$dist/latest.tgz"
  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
}

if [ "$FORCE_UPGRADE" ] ; then
  upgrade
elif [ "$FORCE_UPDATE" ] ; then
  update
else
  `grep $FW_VERSION /etc/openwrt_release &>/dev/null` && update || upgrade
fi
