#!/bin/sh
# /usr/sbin/jd2-tryboot-commit
#
# Promote /boot/firmware/*-candidate files to their active names. Runs only
# when the current boot is a tryboot (firmware exposes this via
# /proc/device-tree/chosen/bootloader/tryboot == 1); otherwise a no-op.
#
# Invoked by jd2-tryboot-confirm.service when /run/m50-ui/ready appears
# (the m50-ui app writes that sentinel after the main window renders).
# Also safe to run manually.

set -eu

FIRMWARE_DIR="${JD2_FIRMWARE_DIR:-/boot/firmware}"
TRYBOOT_FLAG="${JD2_TRYBOOT_FLAG:-/proc/device-tree/chosen/bootloader/tryboot}"
ACTIVE_KERNEL="${FIRMWARE_DIR}/kernel_2712_jd2.img"
ACTIVE_INITRAMFS="${FIRMWARE_DIR}/initramfs_2712_jd2"
CANDIDATE_KERNEL="${FIRMWARE_DIR}/kernel_2712_jd2-candidate.img"
CANDIDATE_INITRAMFS="${FIRMWARE_DIR}/initramfs_2712_jd2-candidate"
CANDIDATE_KVER="${FIRMWARE_DIR}/jd2-candidate-kver"
ACTIVE_KVER="${FIRMWARE_DIR}/jd2-active-kver"
OVERLAY_BASE="vc4-kms-dsi-ti-sn65dsi83-riverdi"
OVERLAY_PATTERN="(${OVERLAY_BASE}(-[^,]*)?|jd2-lcd-[0-9a-f]{32})"
CONFIG_TXT="${FIRMWARE_DIR}/config.txt"
TMP_CONFIG="${CONFIG_TXT}.tmp.$$"
trap 'rm -f "${TMP_CONFIG}"' EXIT HUP INT TERM

if [ ! -r "${TRYBOOT_FLAG}" ]; then
    exit 0
fi

# The device-tree property is a 4-byte BIG-ENDIAN integer, not ASCII: tryboot
# active is the byte sequence 00 00 00 01, never the character "1" (0x31). Read
# the raw bytes in order (od -tx1 is endianness-independent), join to a hex
# string, and parse. A blank/zero value means this boot is not a tryboot trial.
flag_hex=$(od -An -tx1 "${TRYBOOT_FLAG}" 2>/dev/null | tr -d ' \n')
[ -n "${flag_hex}" ] || exit 0
[ "$((0x${flag_hex}))" -ne 0 ] || exit 0

[ -r "${CANDIDATE_KERNEL}" ] || { echo "jd2-tryboot-commit: candidate kernel missing" >&2; exit 1; }
[ -r "${CANDIDATE_INITRAMFS}" ] || { echo "jd2-tryboot-commit: candidate initramfs missing" >&2; exit 1; }
[ -r "${CANDIDATE_KVER}" ] || { echo "jd2-tryboot-commit: candidate KVER marker missing" >&2; exit 1; }
[ -r "${FIRMWARE_DIR}/tryboot.txt" ] || { echo "jd2-tryboot-commit: candidate config missing" >&2; exit 1; }

candidate_kver=$(tr -d '\r\n' < "${CANDIDATE_KVER}")
running_kver=$(uname -r)
[ "${candidate_kver}" = "${running_kver}" ] || {
    echo "jd2-tryboot-commit: running ${running_kver}, candidate marker is ${candidate_kver}" >&2
    exit 1
}

case "${candidate_kver}" in
    *[!a-zA-Z0-9._+-]*) echo "jd2-tryboot-commit: invalid candidate KVER" >&2; exit 1 ;;
esac

# An application can signal readiness while running on a fallback/headless
# desktop. A Riverdi trial must have an enabled, connected LVDS output before
# replacing the working boot files. This checks the display pipeline, not the
# physical panel's image quality.
if grep -Eq "^dtoverlay=${OVERLAY_PATTERN}(,.*)?$" "${FIRMWARE_DIR}/tryboot.txt"; then
    display_ready=0
    for connector in "${JD2_DRM_DIR:-/sys/class/drm}"/card*-LVDS-*; do
        if [ -r "${connector}/status" ] && [ -r "${connector}/enabled" ] && \
           [ "$(cat "${connector}/status")" = connected ] && \
           [ "$(cat "${connector}/enabled")" = enabled ]; then
            display_ready=1
            break
        fi
    done
    [ "${display_ready}" -eq 1 ] || {
        echo "jd2-tryboot-commit: refusing promotion without an enabled LVDS display" >&2
        exit 1
    }
fi

# Keep the full firmware overlay path below the older 63-character limit.
overlay_name="jd2-lcd-$(printf '%s' "${candidate_kver}" | sha256sum | cut -c1-32)"
trial_overlay=''
if cut -d, -f1 "${FIRMWARE_DIR}/tryboot.txt" | grep -Fxq "dtoverlay=${overlay_name}"; then
    trial_overlay="${overlay_name}"
elif cut -d, -f1 "${FIRMWARE_DIR}/tryboot.txt" | \
        grep -Fxq "dtoverlay=${OVERLAY_BASE}-${candidate_kver}"; then
    trial_overlay="${OVERLAY_BASE}-${candidate_kver}"
fi

# Existing legacy candidates retain their original commit behavior.
if [ -n "${trial_overlay}" ]; then
    [ -r "${FIRMWARE_DIR}/overlays/${trial_overlay}.dtbo" ] || {
        echo "jd2-tryboot-commit: candidate display overlay missing" >&2
        exit 1
    }
    grep -Eq "^dtoverlay=${OVERLAY_PATTERN}(,.*)?$" "${CONFIG_TXT}" || {
        echo "jd2-tryboot-commit: active display overlay selection missing" >&2
        exit 1
    }
    sed -E "s%^dtoverlay=${OVERLAY_PATTERN}(,.*)?$%dtoverlay=${trial_overlay}\\3%" \
        "${CONFIG_TXT}" > "${TMP_CONFIG}"
fi

mv -f "${CANDIDATE_KERNEL}" "${ACTIVE_KERNEL}"
mv -f "${CANDIDATE_INITRAMFS}" "${ACTIVE_INITRAMFS}"
if [ -f "${TMP_CONFIG}" ]; then
    mv -f "${TMP_CONFIG}" "${CONFIG_TXT}"
fi
mv -f "${CANDIDATE_KVER}" "${ACTIVE_KVER}"

# The candidate is now the active kernel, so tryboot.txt (which points kernel=
# at the now-gone -candidate image) is stale. Leaving it would make a future
# tryboot load a missing kernel and halt. Drop it.
rm -f "${FIRMWARE_DIR}/tryboot.txt"

sync -f "${FIRMWARE_DIR}" 2>/dev/null || sync
