#!/bin/bash
# SPDX-License-Identifier: LGPL-2.1-or-later
set -euo pipefail

arch=$1 vendor=$2 component=$3 signed=$4
boot=systemd-boot$arch.efi
shim=shim$arch.efi

# Populate bootupd's component even if the ESP is not mounted.
if [[ ! $signed -ef $component/systemd/$boot ]]; then
    ln -Lf "$signed" "$component/systemd/$boot"
fi

if [[ -e /run/ostree-booted || ! -d /sys/firmware/efi ]] ||
    systemd-detect-virt --quiet --container || systemd-detect-virt --quiet --chroot; then
    exit 0
fi

firmware_arch=$(bootctl --print-efi-architecture)
[[ $firmware_arch == "$arch" ]] || exit 0
if ! esp=$(bootctl --print-esp-path); then
    echo "Skipping systemd-boot installation: no accessible ESP." >&2
    exit 0
fi
device=$(findmnt --noheadings --types vfat --output SOURCE --mountpoint "$esp")

tmp=
trap 'if [[ -n $tmp ]]; then rm -f -- "$tmp"; fi' EXIT
same_file() {
    local rc
    if cmp -s "$1" "$2"; then return 0; else rc=$?; fi
    if (( rc > 1 )); then
        echo "Cannot compare $1 with $2." >&2
        exit "$rc"
    fi
    return 1
}

copy_to_esp() {
    local src=$1 dest=$2
    if [[ -f $dest ]] && same_file "$src" "$dest"; then
        return 0
    fi
    mkdir -p "${dest%/*}"
    tmp=$(mktemp "${dest%/*}/.sd-boot.XXXXXXXX")
    install -m 0600 "$src" "$tmp"
    mv -fT "$tmp" "$dest"
    tmp=
}

copy_to_esp "$signed" "$esp/EFI/systemd/$boot"

if ! rpm -q --quiet "shim-$arch"; then
    exit 0
fi
dest=$esp/EFI/$vendor
# F45 shim requires the GRUB RPM even when its second stage is actually sd-boot.
if [[ -f $dest/grub$arch.efi ]]; then
    grep -aFq '#### LoaderInfo: systemd-boot ' "$dest/grub$arch.efi" || {
        rc=$?
        (( rc == 1 )) && exit 0 # Preserve GRUB or another loader.
        exit "$rc"
    }
elif rpm -q --quiet "grub2-efi-$arch"; then
    exit 0
fi
if [[ -f $dest/options.csv ]] && ! same_file "$component/$vendor/options.csv" "$dest/options.csv"; then
    echo "Keeping existing shim configuration in $dest/options.csv." >&2
    exit 0
fi

shim_vr=$(rpm -q --queryformat '%{VERSION}-%{RELEASE}' "shim-$arch")
src=/usr/lib/efi/shim/$shim_vr/EFI/$vendor
copy_to_esp "$src/$shim" "$dest/$shim"
copy_to_esp "$src/mm$arch.efi" "$dest/mm$arch.efi"
sync -f "$esp"
copy_to_esp "$component/$vendor/options.csv" "$dest/options.csv"
sync -f "$esp"

if ! findmnt --noheadings --types efivarfs --options rw --mountpoint /sys/firmware/efi/efivars >/dev/null; then
    echo "Installed systemd-boot on the ESP; EFI variables are not writable." >&2
    exit 0
fi

info=$(lsblk --nodeps --noheadings --raw --paths --output PKNAME,PARTN,PARTUUID "$device")
read -r disk part uuid <<< "$info"
if [[ -z $disk || ! $part =~ ^[0-9]+$ || -z $uuid ]]; then
    echo "Cannot identify the disk and partition backing ESP $esp ($device)." >&2
    exit 1
fi

loader="\\EFI\\$vendor\\$shim"
# efibootmgr --unicode does not always NUL-terminate the argument. Shim needs the terminator.
fallback_args() {
    printf '%s\0' "\\EFI\\systemd\\systemd-boot-fallback$arch.efi" | iconv -f ASCII -t UTF-16LE
}
fallback_hex=$(fallback_args | od -An -v -tx1 | tr -d '[:space:]')

read_entries() {
    local entries entry slot= label path data
    primary_slot= fallback_slot= order=()
    entries=$(efibootmgr --verbose)
    while IFS= read -r entry; do
        if [[ $entry == 'BootOrder: '* ]]; then
            IFS=, read -ra order <<< "${entry#BootOrder: }"
            continue
        elif [[ $entry == Boot* ]]; then
            slot=
            [[ $entry =~ ^Boot([[:xdigit:]]{4})\*?[[:space:]]+(Fedora|Fedora\ \(fallback\))$'\t'(.+)$ ]] || continue
            slot=${BASH_REMATCH[1]^^} label=${BASH_REMATCH[2]} path=${BASH_REMATCH[3],,} data=
        elif [[ -n $slot && $entry == *'data: '* ]]; then
            data=${entry#*data: }
            data=${data// /}
            # efibootmgr may append the hex load options directly to the file path.
            path=${path%"$data"}
        else
            continue
        fi
        [[ $path == *"hd($part,gpt,${uuid,,},"* ]] || continue
        [[ $path == *"/file(${loader,,})"* || ${path%%[[:space:]]*} == *"/${loader,,}" ]] || continue
        if [[ $label == Fedora ]]; then
            primary_slot=$slot
        elif [[ $data == "$fallback_hex" ]]; then
            fallback_slot=$slot
        fi
    done <<< "$entries"
}

read_entries
if [[ -z $primary_slot || -z $fallback_slot ]]; then
    args=(--quiet --disk "$disk" --part "$part" --loader "$loader")
    if [[ -z $primary_slot ]]; then
        efibootmgr "${args[@]}" --create --label Fedora
    fi
    if [[ -z $fallback_slot ]]; then
        # Do not let --create put the fallback ahead of the primary, even temporarily.
        fallback_args | efibootmgr "${args[@]}" --create-only --label 'Fedora (fallback)' --append-binary-args -
    fi
    read_entries
    if [[ -z $primary_slot || -z $fallback_slot ]]; then
        echo "Cannot identify the Fedora and Fedora (fallback) EFI entries on $device." >&2
        exit 1
    fi
fi

new_order=()
seen_primary=no
for slot in "${order[@]}"; do
    case $slot in
        "$primary_slot") new_order+=("$slot" "$fallback_slot"); seen_primary=yes ;;
        "$fallback_slot") [[ $seen_primary == no ]] || exit 0 ;; # Already below Fedora.
        *) new_order+=("$slot") ;;
    esac
done
# If Fedora was deliberately omitted from BootOrder, leave that order alone.
if [[ $seen_primary == yes ]]; then
    IFS=,
    efibootmgr --quiet --bootorder "${new_order[*]}"
fi
