if [ "$1" == "" ]; then
    URLBASE=http://bug.meraki.net/~cliff/ng-image/latest/
else
    URLBASE=$1
fi

echo "this will upgrade from ${URLBASE}"

if [ -f /MERAKI_ARCH ] && ( ! grep mipsel /MERAKI_ARCH ); then
    echo "this is only meant for upgrading netgear nodes"
    exit 1
fi

if cat /dev/mtd/`grep linux /proc/mtd | head -c 4 | tail -c 1` | head -c 4 | grep HDR0; then
    echo 'this is a 2.0.x node'
    echo 'press enter to flash this node'
    read foo foo
    echo 'starting upgrade process ...'
    cat /sbin/* /bin/* /usr/bin/* /usr/sbin/* /sbin/halt /usr/bin/killall /bin/umount > /dev/null
    mount -o remount,ro /dev/root /
    cd /tmp
    wget ${URLBASE}/upgrade-from-2.0.x.trx
    mtd -e linux -r write upgrade-from-2.0.x.trx linux
    exit 1
fi

if cat /dev/mtd/`grep linux /proc/mtd | head -c 4 | tail -c 1` | head -c 4 | grep ELF; then
    echo 'this is (hopefully) a recent build (not 2.0.x or 1.6.x)'
    echo 'press enter to flash this node'
    read foo foo
    cd /tmp
    wget ${URLBASE}/stage2-embedded.elf
    mtd -e linux -r write stage2-embedded.elf linux
    exit 1
fi

echo 'unknown build!'
exit 1
