#!/bin/sh

cd $(dirname $0)
cd linux

abort () {
	dialog --msgbox "Installation aborted." 8 32
	exit 1
}

fail_boot () {
	dialog --msgbox "Unable to boot USB device. Please try again, or report this failure." 10 32
	exit 1
}

fail_write () {
	dialog --msgbox "NAND write failed, you might have to do a full firmware restore, sorry. Please report this failure." 10 32
	exit 1
}

dialog --defaultno --yesno "Do you agree to the terms and conditions?" 8 32 || abort

dialog --menu "Which SPL do you want to flash?" 11 32 3 "1" "Native Priority" "2" "Linux Priority" "3" "Original SPL" 2> choice.txt || abort

if [ ! -d "/usr/local/share/xburst-tools" ]; then
	mkdir -p /usr/local/share/xburst-tools
fi
cp xburst-tools/*.bin /usr/local/share/xburst-tools

case $(cat choice.txt) in
	1)
		dialog --defaultno --yesno "About to write Native Priority SPL to NAND flash, do you want to continue?" 8 32 || abort
		./usbboot -f a330-boot.cfg -c "boot 0" || fail_boot
		./usbboot -f a330-boot.cfg -c "nprog 0 a330-native-spl.bin 0 0 -n" || fail_write
		;;
	2)
		dialog --defaultno --yesno "About to write LINUX SPL to NAND flash, do you want to continue?" 8 32 || abort
		./usbboot -f a330-boot.cfg -c "boot 0" || fail_boot
		./usbboot -f a330-boot.cfg -c "nprog 0 a330-linux-spl.bin 0 0 -n" || fail_write
		;;
	3)
		dialog --defaultno --yesno "About to write ORIGINAL FIRMWARE SPL to NAND flash, do you want to continue?" 8 32 || abort
		./usbboot -f a330-boot.cfg -c "boot 0" || fail_boot
		./usbboot -f a330-boot.cfg -c "nprog 0 a330-original-spl.bin 0 0 -n" || fail_write
		;;
esac

dialog --msgbox "Installation complete, please reboot your Dingoo." 10 32
exit 0

