#!/bin/bash
# Writes the Airoha EN8811H MD32 firmware into eMMC boot1, where U-Boot looks for it.
# Linux does not need this, it loads the same blobs from /lib/firmware.
set -e

dm="/lib/firmware/airoha/EthMD32.dm.bin"
dsp="/lib/firmware/airoha/EthMD32.DSP.bin"
dev="/dev/mmcblk0boot1"
force_ro="/sys/block/mmcblk0boot1/force_ro"

[[ ${EUID} -eq 0 ]] || { echo "must run as root" >&2; exit 1; }
[[ -b ${dev} ]] || { echo "${dev} not present" >&2; exit 1; }
for f in "${dm}" "${dsp}"; do
[[ -f ${f} ]] || { echo "missing ${f}" >&2; exit 1; }
done
[[ $(stat -c%s "${dm}") -eq 16384 ]] || { echo "unexpected size for ${dm}" >&2; exit 1; }
[[ $(stat -c%s "${dsp}") -eq 131072 ]] || { echo "unexpected size for ${dsp}" >&2; exit 1; }

if [[ ${1} != "--yes" ]]; then
echo "This overwrites the first 144 KiB of ${dev}."
echo "Only U-Boot reads it, Linux is unaffected either way."
echo "Re-run with --yes to proceed."
exit 0
fi

ro_was=$(cat "${force_ro}")
trap 'echo "${ro_was}" > "${force_ro}"' EXIT
echo 0 > "${force_ro}"
dd if="${dm}" of="${dev}" bs=16384 count=1 conv=fsync status=none
dd if="${dsp}" of="${dev}" bs=16384 seek=1 conv=fsync status=none
echo "Airoha EN8811H firmware written to ${dev}"
