#!/bin/sh

set -e

if [ $# -lt 2 ]; then
    echo "Usage: $0 <file> <mmc_dev[:part]>"
    echo "*************************************************************"
    echo "* Until u-boot is updated to mainline don't try to write to *"
    echo "* anything other than partition 0. Writing to partition 1   *"
    echo "* will DESTROY your rootfs !                                *"
    echo "*************************************************************"
    exit 1
fi

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

FILE=$1
OUT_FILE=$(basename $1)
MMC_DEV=$2
OUT_PATH=$3

SIZE=$(stat --printf="%s" ${FILE})
HEX_SIZE=$(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

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
# This command will be run when ROM support stream mode
SDPS: boot -f files/u-boot-librem5.imx
FB: ucmd setenv fastboot_buffer 0x43000000
FB: download -f ${FILE}
#FB: ucmd ext4write mmc ${MMC_DEV} 0x43000000 /${OUT_FILE} ${HEX_SIZE}
FB: ucmd save mmc ${MMC_DEV} 0x43000000 /${OUT_FILE} ${HEX_SIZE}
FB: Done
EOF

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

sudo uuu ${UUU_SCRIPT}
