#!/bin/sh

export PATH=/opt/sbin:/opt/bin:$PATH

cat << EOF
This script will upgrade existing Entware packages to Entware-ng.
Please keep in mind:

* Entware-ng is not compatible with old (7+ years) MIPSr1 devices.
    Please, refer to this list if you are not sure about this router
    http://tomatousb.org/doc:build-types#toc3

* Upgrade will be aborted if you are logged on to this console via ssh/telnet
    daemon from Entware, this services will be stopped during upgrade.

* Some of packages may need to be re-configured after upgrade. You may
    (optionally) backup valuable info from /opt folder before upgrade.

Upgrade will be continued in 30 seconds. Press 'Ctrl+c' to abort
EOF

i=0
while [ $i -le 30 ] ; do
  sleep 1
  i=`expr $i + 1`
  echo -n '.'
done

URL=http://andymickey.hopto.org/mirror.pkg.entware.net/binaries/mipsel/installer

echo 'starting upgrade!'
echo '[1/4] Trying to stop running services...'
/opt/etc/init.d/rc.unslung stop

installed_pkgs=$(opkg list_installed | grep -v ^opkg | cut -d ' ' -f 1)
if [ -z "$installed_pkgs" ] ; then
  echo 'No packages seems to be installed before. Exiting...'
  exit 0
fi

echo 'The following packages will be reinstalled after upgrade:'
echo $installed_pkgs
echo '[2/4] Uninstalling existing packages...'
opkg --force-removal-of-essential-packages --force-depends remove $installed_pkgs

dl () {
  # $1 - URL to download
  # $2 - place to store
  # $3 - 'x' if should be executable
  echo -n "Downloading $2... "
  wget -q $1 -O $2
  if [ $? -eq 0 ] ; then
    echo 'success!'
  else
   echo 'failed!'
   exit 1
  fi
  [ -z "$3" ] || chmod +x $2
}

echo '[3/4] Deploying Entware-ng opkg package manager...'
dl $URL/opkg /opt/bin/opkg x
dl $URL/opkg.conf /opt/etc/opkg.conf
dl $URL/profile /opt/etc/profile x
dl $URL/rc.func /opt/etc/init.d/rc.func
dl $URL/rc.unslung /opt/etc/init.d/rc.unslung x

echo '[4/4] Installing new versions of packages...'
opkg update
opkg --force-reinstall install ldconfig findutils $installed_pkgs
ldconfig > /dev/null 2>&1
[ -f /etc/TZ ] && ln -sf /etc/TZ /opt/etc/TZ

echo 'Done. Found a bug? Please report us at'
echo 'https://github.com/Entware-ng/Entware-ng/issues'
