#!/bin/sh
set -e

MC_ITB_PATH=$(find qoriq-mc-binary/ls1088a -name 'mc_ls1088a*itb')
do_env_erase() {
    mtd erase ubootenv
    # Silence U-Boot environment not found (CRC error)
    fw_setenv foo bar 1>/dev/null 2>&1 || :
    fw_setenv fsl_bootcmd_mcinitcmd_set y
    fw_setenv bootcmd "env default -a && saveenv && reset"
    fw_setenv bootdelay 0
}

do_openwrt_nand_flash() {
ubiformat "/dev/${UBIA_MTD_PART}" -f openwrt-nand.ubi
}

mtd erase bl2 && mtd write arm-trusted-firmware/build/ten64/debug/bl2_qspi.pbl bl2
mtd erase bl3 && mtd write arm-trusted-firmware/build/ten64/debug/fip.bin bl3
mtd erase mcfirmware && mtd write "${MC_ITB_PATH}" mcfirmware

mtd erase dpl && mtd write "dpaa2/dpl/eth-dpl-all.dtb" dpl
mtd erase dpc && mtd write "dpaa2/dpc/dpc.0x1D-0x0D.dtb" dpc
mtd erase recovery && mtd write recovery.itb recovery

UBIA_MTD_PART=$(cat /proc/mtd | grep ubia | awk -F ':' '{print $1}')

read -p "Do you wish to reflash the OpenWrt-NAND version (do not say \"y\" if you are currently using it) [y/n] " yn
case $yn in
	[Yy]* ) do_openwrt_nand_flash;;
	*) ;;
esac

read -p "Do you wish to reset the U-Boot environment to default? [y/n] " yn
case $yn in
    [Yy]* ) do_env_erase;;
    *) ;;
esac
