#!/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

if ! ls -d /usr/lib/aosc-os-arm64-boot/dtbs-kernel-$(basename $(ls -d /usr/lib/modules/*-aosc-asahi | sort -rV | head -1 ))/*.dtb 2>&1 >/dev/null; then
    echo "No kernel and device tree available, skipping update ..."
    exit 0
fi

: ${SOURCE:="/usr/lib/asahi-boot/"}
: ${M1N1:="$SOURCE/m1n1.bin"}
: ${U_BOOT:="$SOURCE/u-boot-nodtb.bin"}
: ${TARGET:="$1"}
: ${DTBS:=/usr/lib/aosc-os-arm64-boot/dtbs-kernel-$(basename $(ls -d /usr/lib/modules/*-aosc-asahi | sort -rV | head -1 ))/*.dtb}
: ${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=*|mitigations=*)
                echo "$line" >> "$m1n1config"
                info "  Option: $line"
                ;;
            *)
                warn "  Ignoring unknown option: $line"
                ;;
        esac
    done <$CONFIG
fi

if [ -z "$TARGET" ]; then
    if ! mount_sys_esp /efi; then
        return 0;
    fi
    TARGET="/efi/m1n1/boot.bin"
fi

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

if [ -e "$TARGET" ]; then
    # clobber "${TARGET}.old" only if "$TARGET" changes, use sha512sum to
    # avoid dependency on diffutils
    SHA512_CUR=$(sha512sum "$TARGET"     | cut -d' ' -f1)
    SHA512_NEW=$(sha512sum "$TARGET.new" | cut -d' ' -f1)
    [ "$SHA512_CUR" != "$SHA512_NEW" ] && cp --preserve=timestamps -f "$TARGET" "${TARGET}.old"
fi

mv -f "${TARGET}.new" "$TARGET"

echo "m1n1 updated at ${TARGET}"

# :vim set sts=4 ts=4 sw=4 expandtab:
