#!/usr/bin/bash
# lamboot-bootorder-guard: Keep LamBoot the default after something else took
# the machine back.
#
# Installed by lamboot-install wherever LamBoot is the default boot entry and
# runs from two places:
#   - apt, after every dpkg run (/etc/apt/apt.conf.d/99lamboot-bootorder-guard,
#     DPkg::Post-Invoke), on Debian-family systems;
#   - systemd, once per boot (lamboot-bootorder-guard.service), wherever
#     systemd is present, to undo a takeover that happened outside apt: a manual
#     grub-install, a dpkg-reconfigure, another OS or firmware setup.
#
# Why it exists: shim-signed and the grub-efi-* packages run grub-install from
# their postinst on upgrade, and grub-install puts GRUB's own Boot#### entry
# first in BootOrder. lamboot-install sets debconf grub2/update_nvram=false,
# which Debian's grub-efi postinst honours, but Ubuntu's shim-signed and
# grub-efi-amd64-signed call /usr/lib/grub/grub-multi-install, which never
# reads that question. Ubuntu's grub-install also copies its shim over
# \EFI\BOOT\BOOTX64.EFI.
#
# What it does, and nothing else:
#   - BootOrder: finds the existing Boot#### entry labelled exactly as
#     lamboot-install labelled it, and does nothing if there is none (it never
#     creates one) or if it's already first. Otherwise it moves it to the front,
#     keeping every other entry in its order, but only after confirming the
#     loader chain the entry boots is present on the ESP and matches the install
#     manifest (the same rule lamboot-install's verify_loader_present_for_nvram
#     applies before it touches NVRAM).
#   - Fallback loader: only when LamBoot owns \EFI\BOOT\BOOTX64.EFI (or
#     BOOTAA64.EFI), meaning the install manifest records it because
#     lamboot-install put it there (--fallback, or --root), and the file no
#     longer matches the recorded hash. It's then restored from the LamBoot
#     binary the manifest records with that same hash, and checked afterwards.
#     A fallback path LamBoot doesn't own is never touched, and neither is the
#     installer's .lamboot-backup of the loader that was there before.
#   - logs what it changed to the journal (syslog) and stderr.
# It never deletes an entry and never fails the apt run or the boot: every
# path exits 0.
#
# Settings come from /etc/lamboot/bootorder-guard.conf, written by
# lamboot-install. No settings file, no action. Removed by lamboot-install
# --remove, or turned off for good with --no-make-default.

set -u

GUARD_CONF="${LAMBOOT_GUARD_CONF:-/etc/lamboot/bootorder-guard.conf}"
GUARD_EFIVARS="${LAMBOOT_GUARD_EFIVARS:-/sys/firmware/efi/efivars}"
GUARD_TAG="lamboot-bootorder-guard"
GUARD_DRY_RUN=0

guard_log() {
    # Run by lamboot-bootorder-guard.service, stderr is the journal stream,
    # already tagged with this program's name, so logger would log every line
    # twice. systemd names that stream in JOURNAL_STREAM (device:inode); compare
    # it with the shell's own fd 2, since apt run from a service can inherit
    # the variable with stderr pointing elsewhere.
    if [ -n "${JOURNAL_STREAM:-}" ] \
       && [ "$(stat -L -c '%d:%i' "/proc/$$/fd/2" 2>/dev/null)" = "$JOURNAL_STREAM" ]; then
        printf '%s\n' "$*" >&2
        return 0
    fi
    printf '%s: %s\n' "$GUARD_TAG" "$*" >&2
    command -v logger >/dev/null 2>&1 && logger -t "$GUARD_TAG" -- "$*" 2>/dev/null
    return 0
}

# key=value reader that never executes the file (same contract as
# lamboot-install's read_keyval_field).
guard_conf_value() {
    local key="$1" line
    [ -r "$GUARD_CONF" ] || return 0
    line=$(grep -E "^${key}=" "$GUARD_CONF" 2>/dev/null | tail -n1)
    [ -n "$line" ] || return 0
    line=${line%$'\r'}
    printf '%s' "${line#*=}"
}

# Print the bootnum of the entry whose description is exactly LABEL. Matches
# lamboot-install's find_lamboot_entry: the description ends at the first TAB
# or end of line, and the active flag is `*` or a space. An active entry wins
# over an inactive one with the same label, so a stale disabled duplicate isn't
# the one promoted while the real entry stays behind GRUB.
guard_find_entry() {
    local label="$1" re tab list hit
    tab=$(printf '\t')
    re='^Boot\([0-9A-Fa-f]\{4\}\)\([* ]\) '"$label"' *\('"$tab"'.*\)\{0,1\}$'
    list=$(efibootmgr 2>/dev/null) || return 0
    hit=$(printf '%s\n' "$list" | sed -n "s/${re}/\1\2/p" | grep '\*$' | head -1)
    [ -n "$hit" ] || hit=$(printf '%s\n' "$list" | sed -n "s/${re}/\1\2/p" | head -1)
    printf '%s\n' "${hit:0:4}"
}

guard_boot_order() {
    efibootmgr 2>/dev/null | grep '^BootOrder:' | cut -d: -f2 | tr -d ' '
}

guard_label_of() {
    efibootmgr 2>/dev/null \
        | sed -n "s/^Boot$1[* ] \([^$(printf '\t')]*\).*/\1/p" | head -1
}

# The hash the install manifest records for ESP-relative path REL, if any.
guard_manifest_hash() {
    local mf="$1" rel="$2"
    awk -v r="$rel" '$2 == r { sub(/^sha256:/, "", $1); print $1; exit }' "$mf" 2>/dev/null
}

guard_sha256() {
    [ -f "$1" ] || return 0
    sha256sum "$1" 2>/dev/null | cut -d' ' -f1
}

# Every loader file the entry traverses must exist on the ESP and, where the
# manifest records a hash for it, match that hash. A missing or changed loader
# means LamBoot isn't in a state to be the default, so the guard leaves NVRAM
# alone rather than point firmware at it.
guard_loader_chain_intact() {
    local esp="$1" manifest="$2"; shift 2
    local rel want got
    [ "$#" -gt 0 ] || return 1
    for rel in "$@"; do
        [ -f "${esp}/${rel}" ] || { guard_log "loader ${rel} missing on the ESP; leaving BootOrder alone"; return 1; }
        [ -f "${esp}/${manifest}" ] || continue
        want=$(guard_manifest_hash "${esp}/${manifest}" "$rel")
        [ -n "$want" ] || continue
        command -v sha256sum >/dev/null 2>&1 || continue
        got=$(guard_sha256 "${esp}/${rel}")
        if [ -n "$got" ] && [ "$got" != "$want" ]; then
            guard_log "loader ${rel} doesn't match the install manifest; leaving BootOrder alone"
            return 1
        fi
    done
    return 0
}

# Put LamBoot's firmware fallback loader back when something replaced it, but
# only when LamBoot owns that path: The install manifest records it, because
# lamboot-install put it there. The installer copied it from a LamBoot binary it
# also recorded, so the manifest names the source by the same hash.
guard_restore_fallback() {
    local esp="$1" manifest="$2"
    local mf="${esp}/${manifest}" rel want got src tmp
    [ -f "$mf" ] || return 0
    command -v sha256sum >/dev/null 2>&1 || return 0
    rel=$(awk '$2 ~ /^EFI\/BOOT\/BOOT(X64|AA64)\.EFI$/ { print $2; exit }' "$mf" 2>/dev/null)
    [ -n "$rel" ] || return 0
    want=$(guard_manifest_hash "$mf" "$rel")
    [ -n "$want" ] || return 0
    got=$(guard_sha256 "${esp}/${rel}")
    [ "$got" = "$want" ] && return 0

    src=$(awk -v h="sha256:${want}" -v r="$rel" \
        '$1 == h && $2 != r && $2 ~ /^EFI\/LamBoot\// { print $2; exit }' "$mf" 2>/dev/null)
    if [ -z "$src" ] || [ "$(guard_sha256 "${esp}/${src}")" != "$want" ]; then
        guard_log "${rel} no longer matches the install manifest, and no LamBoot binary on the ESP matches what was recorded for it; leaving it alone"
        return 0
    fi
    local was="missing"
    [ -n "$got" ] && was="sha256 ${got:0:16}"
    if (( GUARD_DRY_RUN )); then
        guard_log "would restore ${rel} (now ${was}) from ${src}"
        return 0
    fi
    tmp="${esp}/${rel}.lamboot-tmp"
    if mkdir -p "$(dirname "${esp}/${rel}")" 2>/dev/null \
       && cp -- "${esp}/${src}" "$tmp" 2>/dev/null \
       && mv -f -- "$tmp" "${esp}/${rel}" 2>/dev/null \
       && [ "$(guard_sha256 "${esp}/${rel}")" = "$want" ]; then
        guard_log "${rel} had been replaced (was ${was}); restored LamBoot's copy from ${src}"
    else
        rm -f -- "$tmp" 2>/dev/null
        guard_log "couldn't restore ${rel} from ${src}; the firmware fallback path isn't LamBoot"
    fi
    return 0
}

# The new BootOrder: BOOTNUM first, every other entry after it in its old order.
guard_reordered() {
    local bootnum="$1" order="$2" out="$1" e
    local -a ents
    IFS=',' read -ra ents <<< "$order"
    for e in "${ents[@]}"; do
        [ -n "$e" ] && [ "$e" != "$bootnum" ] && out="${out},${e}"
    done
    printf '%s' "$out"
}

# Move the LamBoot entry back to the front of BootOrder if it isn't first.
guard_restore_bootorder() {
    local label="$1" esp="$2" manifest="$3" loaders="$4" esp_mounted="$5"
    [ -d "$GUARD_EFIVARS" ] || return 0
    command -v efibootmgr >/dev/null 2>&1 || return 0

    local bootnum order
    bootnum=$(guard_find_entry "$label")
    [ -n "$bootnum" ] || return 0
    order=$(guard_boot_order)
    # An empty read (efibootmgr failing between the two calls, or no BootOrder
    # at all) would make LamBoot the only entry and drop every other one.
    if [ -z "$order" ]; then
        guard_log "couldn't read BootOrder; leaving it alone"
        return 0
    fi
    # Fast path for the usual case: nothing moved, so stay silent.
    [ "${order%%,*}" = "$bootnum" ] && return 0

    if ! (( esp_mounted )); then
        guard_log "Boot${bootnum} (${label}) isn't first, but the ESP isn't mounted at ${esp}; leaving BootOrder alone"
        return 0
    fi
    # shellcheck disable=SC2086  # LOADERS is a space-separated list of ESP-relative paths
    guard_loader_chain_intact "$esp" "$manifest" $loaders || return 0

    local new_order first_label
    new_order=$(guard_reordered "$bootnum" "$order")
    first_label=$(guard_label_of "${order%%,*}")
    if (( GUARD_DRY_RUN )); then
        guard_log "would restore Boot${bootnum} (${label}) to first: BootOrder ${order:-empty} -> ${new_order}"
        return 0
    fi
    if efibootmgr --bootorder "$new_order" --quiet >/dev/null 2>&1; then
        guard_log "Boot${order%%,*}${first_label:+ (${first_label})} had been moved ahead of ${label}; restored Boot${bootnum} to first: BootOrder ${order:-empty} -> ${new_order}"
    else
        guard_log "efibootmgr couldn't write BootOrder ${new_order}; ${label} isn't the default"
    fi
    return 0
}

guard_main() {
    local arg
    for arg in "$@"; do
        case "$arg" in
            --apt|--boot) ;;
            --dry-run) GUARD_DRY_RUN=1 ;;
            -h|--help)
                printf 'usage: %s [--apt|--boot] [--dry-run]\n' "$GUARD_TAG"
                return 0 ;;
        esac
    done

    [ -r "$GUARD_CONF" ] || return 0

    local label esp manifest loaders
    label=$(guard_conf_value LABEL)
    esp=$(guard_conf_value ESP)
    manifest=$(guard_conf_value MANIFEST)
    manifest=${manifest:-EFI/LamBoot/.install-manifest}
    loaders=$(guard_conf_value LOADERS)
    [ -n "$label" ] && [ -n "$esp" ] || return 0

    # Nothing on the ESP is trusted unless the ESP is really mounted there; an
    # unmounted mountpoint can hold stale files on the root filesystem.
    local esp_mounted=0
    mountpoint -q "$esp" 2>/dev/null && esp_mounted=1

    (( esp_mounted )) && guard_restore_fallback "$esp" "$manifest"
    guard_restore_bootorder "$label" "$esp" "$manifest" "$loaders" "$esp_mounted"
    return 0
}

if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    guard_main "$@"
    exit 0
fi
