#!/bin/sh

set -e

TEMPDIR=$(mktemp -d)
cd "$TEMPDIR"
wget https://files.embeddedts.com/ts-socket-macrocontrollers/ts-4300-linux/bootloader/ts4300-singleboot-latest.bin -O singleboot.bin
wget https://files.embeddedts.com/ts-socket-macrocontrollers/ts-4300-linux/bootloader/ts4300-singleboot-latest.bin.md5 -O singleboot.bin.md5
wget https://files.embeddedts.com/ts-socket-macrocontrollers/ts-4300-linux/bootloader/ts4300-u-boot-initial-env-latest.txt -O env.txt
wget https://files.embeddedts.com/ts-socket-macrocontrollers/ts-4300-linux/bootloader/ts4300-u-boot-initial-env-latest.txt.md5 -O env.txt.md5

# Confirm md5sum
echo "$(awk '{print $1}' singleboot.bin.md5)  singleboot.bin" | md5sum -c -
echo "$(awk '{print $1}' env.txt.md5)  env.txt" | md5sum -c -

set +e
if command -v mkenvimage &> /dev/null; then
    MKENVIMAGE_PRESENT=1
else
    MKENVIMAGE_PRESENT=0
fi
set -e

echo 0 > /sys/class/block/mmcblk0boot0/force_ro
dd if=singleboot.bin bs=1M of=/dev/mmcblk0boot0

if [ "$MKENVIMAGE_PRESENT" = "1" ]; then
	mkenvimage -s 0x4000 -o env.bin env.txt
	dd if=env.bin bs=1048576 seek=3 of=/dev/mmcblk0boot0
else
	echo "U-boot updated, but mkenvimage is not installed so the u-boot env"
	echo "was not updated. To update by hand, stop at a u-boot prompt on the"
	echo "next boot and run:"
	echo "    env default -a; env save"
	exit 0
fi

echo "Updated U-boot successfully!"
