#!/bin/bash -e

# Usage:
#  wget -q -O - http://files.embeddedts.com/ts-arm-sbc/ts-7180-linux/u-boot/update-uboot-new-env | bash

set -x
MODEL="$(fw_printenv --noheader model)"
[ -z "$MODEL" ] && echo "Board model cannot be determined." >&2 && exit 7

[ "${MODEL}" == "7180" ] && EMMC_DEV=mmcblk1boot0 || EMMC_DEV=mmcblk0boot0

U_BOOT_URL=https://files.embeddedts.com/ts-arm-sbc/ts-${MODEL}-linux/u-boot

#FILES="$(mktemp -d)"
FILES=tmp && [ ! -d $FILES ] && mkdir $FILES
cd "$FILES"
wget ${U_BOOT_URL}/SPL-latest || exit 1
wget ${U_BOOT_URL}/SPL-latest.md5 || exit 2
wget ${U_BOOT_URL}/u-boot-ts${MODEL}-latest.img || exit 3
wget ${U_BOOT_URL}/u-boot-ts${MODEL}-latest.img.md5 || exit 4

# Verify all files md5s match
md5sum -c SPL-latest.md5 || exit 5
md5sum -c u-boot-dtb-latest.img.md5 || exit 6

echo 0 > /sys/block/${EMMC_DEV}/force_ro
dd if=SPL-${MODEL}-latest of=/dev/${EMMC_DEV} bs=512 seek=2
dd if=u-boot-${MODEL}-latest.img of=/dev/${EMMC_DEV} bs=512 seek=138 
sync
echo 1 > /sys/block/${EMMC_DEV}/force_ro

set +x
echo "Latest u-boot installed!"
