#!/bin/sh

set -e

if [ $# -lt 1 ]; then
    echo "Usage: $0 <file>"
    echo "\tWrites a file to the NOR flash"
    exit 1
fi

cleanup()
{
    [ -z "${UUU_SCRIPT}" ] || rm -f "${UUU_SCRIPT}" 
}
trap cleanup EXIT

FILE=$1

SIZE=$(stat --printf="%s" ${FILE})
SIZE=$(echo "(${SIZE}/4096+1)*4096" | bc)
HEX_SIZE=$(printf "0x%x" ${SIZE})
SIZE=$(echo "${SIZE}/4" | bc)
HEX_WORDS=$(printf "0x%x" ${SIZE})
UUU_SCRIPT=$(mktemp -p ./)

cat << EOF > ${UUU_SCRIPT}
uuu_version 1.0.1
# Use uboot to write a file to the rootfs
CFG: FB:  -vid 0x316d -pid 0x4c05
CFG: SDP: -chip MX8MQ -compatible MX8MQ -vid 0x316d -pid 0x4c05

SDP: boot -f files/u-boot-librem5.imx
# This command will be run when use SPL
SDPU: delay 1000
SDPU: write -f files/u-boot-librem5.imx -offset 0x57c00
SDPU: jump
SDPV: delay 1000
SDPV: write -f files/u-boot-librem5.imx -skipspl
SDPV: jump
FB: ucmd setenv fastboot_buffer 0x43000000
FB: download -f ${FILE}
FB: ucmd sf probe
FB: ucmd sf erase 0 ${HEX_SIZE}
FB: delay 2000
FB: ucmd sf write 0x43000000 0 ${HEX_SIZE}
FB: delay 2000
FB: ucmd sf read 0x44000000 0 ${HEX_SIZE}
FB: delay 2000
FB: ucmd cmp 0x43000000 0x44000000 ${HEX_WORDS}
FB: Done
EOF

echo "About to run ${UUU_SCRIPT}"
cat ${UUU_SCRIPT}

uuu -v ${UUU_SCRIPT}
