#!/bin/sh -e

URL="http://files.embeddedts.com/ts-socket-macrocontrollers/ts-4300-linux/fpga/ts4300-fpga-latest.itb"
COMPATIBLE="technologic,ts4300"

# Read the compatible string and replace null characters with newlines
ACTUAL_COMPATIBLE=$(cat /sys/firmware/devicetree/base/compatible 2>/dev/null | tr '\0' ' ')

if ! echo "$ACTUAL_COMPATIBLE" | tr ' ' '\n' | grep -qx "$COMPATIBLE"; then
    echo "Unsupported system, expected \"$COMPATIBLE\", got \"$ACTUAL_COMPATIBLE\""
    exit 1
fi

echo 0 > /sys/block/mmcblk0boot0/force_ro
wget -qO- "$URL" | dd of=/dev/mmcblk0boot0 bs=512 seek=$((0x340000 / 512))
echo 1 > /sys/block/mmcblk0boot0/force_ro
sync

echo "Update prepared, reboot to apply"
