boot_block_size_r=0x200000
boot_block_size=0x1000
bootloader_file=u-boot-dtb-tegra.bin
spi_size=0x400000
boot_dev=0
boot_interface=mmc

flash_uboot=echo Preparing RAM;
	mw ${kernel_addr_r} 0 ${boot_block_size_r};
		mw ${ramdisk_addr_r} 0 ${boot_block_size_r};
		echo Reading BCT;
		mmc dev 0 1;
		mmc read ${kernel_addr_r} 0 ${boot_block_size};
		echo Reading bootloader;
		if load ${boot_interface} ${boot_dev}:1 ${ramdisk_addr_r} ${bootloader_file};
		then echo Calculating bootloader size;
			size ${boot_interface} ${boot_dev}:1 ${bootloader_file};
			ebtupdate ${kernel_addr_r} ${ramdisk_addr_r} ${filesize};
			echo Writing bootloader to eMMC;
			mmc dev 0 1;
			mmc write ${kernel_addr_r} 0 ${boot_block_size};
			mmc dev 0 2;
			mmc write ${ramdisk_addr_r} 0 ${boot_block_size};
			echo Bootloader written successfully;
			pause 'Press ANY key to reboot device...'; reset;
		else echo Reading bootloader failed;
			pause 'Press ANY key to return to bootmenu...'; bootmenu; fi

update_spi=sf probe 0:1;
	echo Dumping current SPI flash content ...;
	sf read ${kernel_addr_r} 0x0 ${spi_size};
	if fatwrite mmc 1:1 ${kernel_addr_r} spi-flash-backup.bin ${spi_size};
	then echo SPI flash content was successfully written into spi-flash-backup.bin;
		echo Reading SPI flash binary;
		if load mmc 1:1 ${kernel_addr_r} repart-block.bin;
		then echo Writing bootloader into SPI flash;
			sf probe 0:1;
			sf update ${kernel_addr_r} 0x0 ${spi_size};
			echo Bootloader SUCCESSFULLY written into SPI flash;
			pause 'Press ANY key to reboot...'; reset;
		else echo Preparing RAM;
			mw ${kernel_addr_r} 0 ${boot_block_size_r};
			mw ${ramdisk_addr_r} 0 ${boot_block_size_r};
			echo Reading BCT;
			sf read ${kernel_addr_r} 0x0 ${boot_block_size_r};
			echo Reading bootloader;
			if load mmc 1:1 ${ramdisk_addr_r} ${bootloader_file};
			then echo Calculating bootloader size;
				size mmc 1:1 ${bootloader_file};
				ebtupdate ${kernel_addr_r} ${ramdisk_addr_r} ${filesize};
				echo Writing bootloader into SPI flash;
				sf probe 0:1;
				sf update ${kernel_addr_r} 0x0 ${boot_block_size_r};
				sf update ${ramdisk_addr_r} ${boot_block_size_r} ${boot_block_size_r};
				echo Bootloader written SUCCESSFULLY;
				pause 'Press ANY key to reboot...'; reset;
			else echo Reading bootloader failed;
				pause 'Press ANY key to reboot...'; reset; fi;
		fi;
	else echo SPI flash backup FAILED! Aborting ...;
		pause 'Press ANY key to reboot...'; reset; fi
