#!/bin/sh
# Write this distribution's edk2-rk3588 firmware for the running board to SPI.
#
#   flash-rk3588-edk2-spi --secure-boot    [mtd-device]   (default /dev/mtd0)
#   flash-rk3588-edk2-spi --no-secure-boot [mtd-device]
#
# Every board has two images, Secure Boot enabled and not. The choice is
# REQUIRED: writing firmware must never switch a board's Secure Boot state as a
# side effect nobody asked for.
#
# THE BOARD IS CHOSEN HERE, NOT BY THE CALLER: the device tree's compatible
# names it, and a board this package has no image for is refused. A wrong
# bootloader in SPI is recoverable only through maskrom and another computer.
#
# The images are padded to the start of the firmware's variable store, so
# flashcp rewrites everything below it and leaves the stored settings -- and
# enrolled Secure Boot keys -- as they are. Requires mtd-utils.
set -e
DIR=/usr/share/scutarius-firmware-rk3588-edk2
case "${1:-}" in
  --secure-boot)    VARIANT=secureboot ;;
  --no-secure-boot) VARIANT=nosecureboot ;;
  *) echo "usage: $0 --secure-boot|--no-secure-boot [mtd-device]" >&2; exit 2 ;;
esac
MTD=${2:-/dev/mtd0}

COMPAT=$(tr '\0' '\n' < /proc/device-tree/compatible 2>/dev/null | head -1)
case "$COMPAT" in
  radxa,rock-5b) IMG=rock-5b-$VARIANT.img ;;
  *) echo "refusing: this package has no firmware image for board '$COMPAT'" >&2; exit 1 ;;
esac

[ -f "$DIR/$IMG" ] || { echo "refusing: $DIR/$IMG is not installed" >&2; exit 1; }
[ -c "$MTD" ] || { echo "no MTD device $MTD (SPI NOR not probed?)" >&2; exit 1; }
cd "$DIR" && sha256sum -c --ignore-missing SHA256SUMS
echo "flashing $IMG to $MTD (board: $COMPAT)"
exec flashcp -v "$DIR/$IMG" "$MTD"
