#! /bin/sh

Usage()
{
	echo "-h : Prints this message"
	echo "-b : Selects boot device (hsmmc/nand)"
	echo "-c : Selects configblock partition only update"
	echo "-d : Selects debug boot loader without flashing"
	echo "-k : Selects kernel partition only update"
#	echo "-r : Selects RAM size (256/512)"
	echo "-u : Selects boot loader partition only update"
}

BOOT_DEVICE=hsmmc
CFGBLOCK_ONLY=0
DEBUG_ONLY=0
KERNEL_ONLY=0
#RAM_SIZE=256
UBOOT_ONLY=0
IMAGEFILE=APP.ext3

while getopts "b:cdhkr:u" Option ; do
	case $Option in
		h) Usage
			# Exit if only usage (-h) was specfied.
			if [[ $# -eq 1 ]] ; then
				exit 10
			fi
			exit 0
			;;
		b) BOOT_DEVICE=$OPTARG
			;;
		c) CFGBLOCK_ONLY=1
			;;
		d) DEBUG_ONLY=1
			;;
		k) KERNEL_ONLY=1
			;;
#		r) RAM_SIZE=$OPTARG
#			;;
		u) UBOOT_ONLY=1
			;;
	esac
done

if [ ${DEBUG_ONLY} -eq 1 ] ; then
	PART_CFG=./nand-flash.cfg
	BCT=./apalis_t30_12MHz_MT41K512M8RH-125_533MHz.bct
	# Debugging only, writes only u-boot to RAM and executes it, assumes a valid BCT on target
	# sudo nvflash/nvflash --bl bin/u-boot.bin --go
	# Debugging only, writes only u-boot to RAM and executes it, downloads also the BCT on target
	sudo nvflash/nvflash --bct ${BCT} --setbct --configfile ${PART_CFG} ${ODMDATA} --create --bl bin/u-boot.bin --go
	exit 0
fi

cd bin

if [ ${BOOT_DEVICE} = "hsmmc" ] ; then
	PART_CFG=../emmc-flash.cfg
	BCT=../apalis_t30_12MHz_MT41K512M8RH-125_533MHz.bct
fi

if [ ${CFGBLOCK_ONLY} -ne 1 ] && [ ${KERNEL_ONLY} -ne 1 ] && [ ${UBOOT_ONLY} -ne 1 ] ; then
	if [ ${BOOT_DEVICE} = "hsmmc" ] ; then
		#build ${IMAGEFILE} if it does not exist
		[ -e "${IMAGEFILE}" ] || sudo ./genext3fs.sh -d ../rootfs -b 384 ${IMAGEFILE}
	fi

	# Full flashing
	sudo ../nvflash/nvflash --bct ${BCT} --setbct --configfile ${PART_CFG} --odmdata 0x40080105 --create --bl bootloader.bin --go

	if [ ${BOOT_DEVICE} = "hsmmc" ] ; then
		echo 
#		sudo rm ${IMAGEFILE}
	fi
else
	# Partial flashing
	if ([ ${CFGBLOCK_ONLY} -eq 1 ] && [ ${KERNEL_ONLY} -ne 1 ] && [ ${UBOOT_ONLY} -ne 1 ]) || ([ ${CFGBLOCK_ONLY} -ne 1 ] && [ ${KERNEL_ONLY} -eq 1 ] && [ ${UBOOT_ONLY} -ne 1 ]) || ([ ${CFGBLOCK_ONLY} -ne 1 ] && [ ${KERNEL_ONLY} -ne 1 ] && [ ${UBOOT_ONLY} -eq 1 ]) ; then
		if [ ${UBOOT_ONLY} -eq 1 ] ; then
			# U-Boot flashing
			sudo ../nvflash/nvflash --bl bootloader.bin --download 4 u-boot.bin
		fi
		if [ ${KERNEL_ONLY} -eq 1 ] ; then
			# Linux kernel flashing
			sudo ../nvflash/nvflash --bl bootloader.bin --download 7 uImage
		fi
		if [ ${CFGBLOCK_ONLY} -eq 1 ] ; then
			# Configuration block flashing
			../nvflash/nvflash --bl bootloader.bin --download 8 configblock_${RAM_SIZE}.bin
		fi
	else
		echo "Only one of -c, -k or -u is possible at any one time!"
	fi
fi
