#!/bin/sh
# SPDX-License-Identifier: MIT

set -e

[ -e /etc/default/update-m1n1 ] && . /etc/default/update-m1n1

[ -n "$M1N1_UPDATE_DISABLED" ] && exit 0

if [ -e "$(dirname "$0")"/functions.sh ]; then
    . "$(dirname "$0")"/functions.sh
else
    . /usr/share/asahi-scripts/functions.sh
fi

: ${SOURCE:="/usr/lib/asahi-boot/"}
: ${M1N1:="$SOURCE/m1n1.bin"}
: ${U_BOOT:="$SOURCE/u-boot-nodtb.bin"}
: ${TARGET:="$1"}
: ${CONFIG:=/etc/m1n1.conf}

if [ -z "$DTBS" ]; then
    warn "ERROR: DTBS config unset or empty, see `/etc/default/update-m1n1`"
    exit 1
fi

umount=false

m1n1config=/run/m1n1.conf
>"$m1n1config"

if [ -e "$CONFIG" ]; then
    info "Reading m1n1 config from $CONFIG:"
    while read line; do
        case "$line" in
            "") ;;
            \#*) ;;
            chosen.*=*|display=*)
                echo "$line" >> "$m1n1config"
                info "  Option: $line"
                ;;
            *)
                warn "  Ignoring unknown option: $line"
                ;;
        esac
    done <$CONFIG
fi

if [ -z "$TARGET" ]; then
    mount_sys_esp /run/.system-efi
    TARGET="/run/.system-efi/m1n1/boot.bin"
    umount=true
fi

cat "$M1N1" $DTBS >"${TARGET}.new"
gzip -c "$U_BOOT" >>"${TARGET}.new"
cat "$m1n1config" >>"${TARGET}.new"

[ -e "$TARGET" ] && mv -f "$TARGET" "${TARGET}.old"
mv -f "${TARGET}.new" "$TARGET"

echo "m1n1 updated at ${TARGET}"
$umount && umount /run/.system-efi
true
