#!/bin/sh

# Upgrade script that pulls, verifies and updates images.
# Version: 2015-07-12


# Notes:
# - busybox does not seem to understand default variable settings like bash
# 

echo -e "\
:: Specify your device. Valid options are as follows:
    * 3700	Netgear WNDR3700 v1
    * 3700v2	Netgear WNDR3700 v2
    * 1043	TP-Link TL-WR1043ND v1
    * 1043v2	TP-Link TL-WR1043ND v2
    * 841	TP-Link TL-WR841N(D) v7 \n"

read DEVICE

# Model name and image definitions
case "$DEVICE" in 
	3700)
		MODEL="Netgear WNDR3700"
		FWURL="http://volatilesystems.org/dl/openwrt/15.05/latest/ar71xx/openwrt-ar71xx-generic-wndr3700-squashfs-sysupgrade.bin" 
		UPGRSTRING="wndr3700-squashfs-sysupgrade"
		;;
	3700v2)
		MODEL="Netgear WNDR3700 v2"	
		FWURL="http://volatilesystems.org/dl/openwrt/15.05/latest/ar71xx/openwrt-ar71xx-generic-wndr3700v2-squashfs-sysupgrade.bin"
		UPGRSTRING="wndr3700v2-squashfs-sysupgrade"
		;;
	1043)
		MODEL="TP-Link TL-WR1043ND v1"
		FWURL="http://volatilesystems.org/dl/openwrt/15.05/latest/ar71xx/openwrt-ar71xx-generic-tl-wr1043nd-v1-squashfs-sysupgrade.bin"
		UPGRSTRING="tl-wr1043nd-v1-squashfs-sysupgrade"
		;;
	1043v2)
		MODEL="TP-Link TL-WR1043ND v2"
		FWURL="http://volatilesystems.org/dl/openwrt/15.05/latest/ar71xx/openwrt-ar71xx-generic-tl-wr1043nd-v2-squashfs-sysupgrade.bin"
		UPGRSTRING="tl-wr1043nd-v2-squashfs-sysupgrade"
		;;
	841)
		MODEL="TP-Link TL-WR841N(D) v7"
		FWURL="http://volatilesystems.org/dl/openwrt/15.05/latest/ar71xx/openwrt-ar71xx-generic-tl-wr841nd-v7-squashfs-sysupgrade.bin"
		UPGRSTRING="tl-wr841nd-v7-squashfs-sysupgrade"
		;;
esac

# Grab the image and checksum file
echo ":: Model selected: $MODEL"
echo -e ":: Now downloading checksum file and upgrade image for $MODEL to ramdisk... \n"

cd /tmp/
wget -c http://volatilesystems.org/dl/openwrt/15.05/latest/ar71xx/md5sums "$FWURL"

# Save checksum to a temporary file for easier validation
echo -e ":: Calculating checksum... \n"
grep $UPGRSTRING md5sums > checksum.tmp

if md5sum -c checksum.tmp
then
	echo ":: Image integrity checked; proceeding with flash."
	sysupgrade "$(basename $FWURL)"
else
	echo ":: Image corrupt or checksum invalid; ABORTING."
	exit 1
fi


