#!/usr/bin/env bash
# Copyright (C) 2026 Vasiliy Stelmachenok <ventureo@cachyos.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

# From systemd-boot-manager
function generate_cmdline() {
    local srcdev \
        srcdev_uuid \
        srcdev_partuuid \
        srcdev_fsroot \
        root_fstype \
        cryptdevice_uuid \
        zpool \
        zpool_device \
        top_level_uuid \
        options

    srcdev="$(findmnt -vno SOURCE /)"
    srcdev_uuid="$(findmnt -no UUID /)"
    srcdev_partuuid="$(findmnt -no PARTUUID /)"
    srcdev_fsroot="$(findmnt -no FSROOT /)"
    root_fstype="$(findmnt -no FSTYPE /)"

    if [[ "$srcdev" == "overlay" ]]; then
        echo "Your root is overlay, not possible to detect device" >&2
        return 1
    fi

    if [[ -n "$srcdev_uuid" ]]; then
        options="root=UUID=${srcdev_uuid}"
    elif [[ -n "$srcdev_partuuid" ]]; then
        options="root=PARTUUID=${srcdev_partuuid}"
    else
        options="root=${srcdev}"
    fi

    case "${root_fstype}" in
        zfs)
            options="zfs=${srcdev}"
            ;;
        btrfs)
            options+=" rootflags=subvol=${srcdev_fsroot}"
            ;;
    esac

    top_level_uuid="${srcdev_uuid}"

    if [[ "${root_fstype}" = "zfs" ]]; then
        zpool="${srcdev%%/*}"
        zpool_device="$(zpool status -LP "${zpool}" | grep "/dev/" | awk '{print $1}')"
        top_level_uuid="$(lsblk -no UUID "${zpool_device}")"
    fi

    while read -r devname devtype; do
        if [[ "$devtype" = "crypt" ]]; then
            cryptdevice_uuid="$(blkid -o value -s UUID \
                "$(cryptsetup status "${devname}" \
                    | grep device \
                    | awk '{print $2}'
                )"
            )"
            options+=" cryptdevice=UUID=${cryptdevice_uuid}:${devname}"
            break
        fi
    done < <(lsblk -nslo NAME,TYPE /dev/disk/by-uuid/"${top_level_uuid}" 2>/dev/null)

    echo "${options}"
}

function find_recovery_entry() {
    local target_uuid="${1}"
    local target_path="${2}"
    local uuid boot path

    if ! output="$(efibootmgr 2>/dev/null)"; then
        echo "Failed to get efibootmgr output" >&2
        return 1
    fi

    while read -r line; do
        uuid="${line%%/*}"
        uuid="${uuid%,*}"
        uuid="${uuid%,*}"
        uuid="${uuid##*,}"
        [[ "${uuid}" == "${target_uuid}" ]] || continue

        path=${line##*/}
        [[ "${path}" == "${target_path}" ]] || continue

        boot="${line%%$'*'*}"
        boot="${boot#Boot}"
        [[ "${boot}" =~ [A-F0-9]+ ]] || continue

        echo "${boot}" && return 0
    done <<< "$output"

    return 1
}

function create_boot_entry() {
    local path="${1}"
    local esp="${2}"
    local device disk partition order uuid entry

    if ! command -v efibootmgr &>/dev/null; then
        echo "efibootmgr not found, skipping creating EFI entry..."
        return 0
    fi

    if ! uuid="$(findmnt -vno PARTUUID "${esp}")"; then
        echo "Failed to detect ESP partition UUID" >&2
        return 1
    fi

    # Entry already exists for current installation, nothing to do
    if [[ -n "$(find_recovery_entry "$uuid" "$path")" ]]; then
        return 0
    fi

    while read -r line; do
        if [[ "$line" == /dev/* ]]; then
            device="${line}"
            break
        fi
    done < <(findmnt -vno SOURCE "${esp}" || true)

    if [[ -z "${device:-}" ]]; then
        echo "Failed to detect ESP partition device" >&2
        return 1
    fi

    device="${device#/dev/}"

    if ! disk="$(readlink -f "/sys/class/block/${device}" 2>/dev/null)"; then
        echo "Failed to detect ESP disk device" >&2
        return 1
    fi

    disk="${disk%/*}"
    disk="${disk##*/}"

    if ! partition="$(cat "/sys/class/block/${device}/partition" 2>/dev/null)"; then
        echo "Failed to detect ESP partition number" >&2
        return 1
    fi

    if ! efibootmgr --create-only \
        --disk "/dev/${disk}" \
        --part "${partition}" \
        --loader "${path}" \
        --label 'CachyOS Recovery' \
        --unicode 1>/dev/null; then
        echo "Failed to execute efibootmgr" >&2
        return 1
    fi

    if ! order="$(efibootmgr 2>/dev/null | grep -Po "^BootOrder:\s+\K(.*)" || false)"; then
        echo "Failed to detect boot EFI order" >&2
        return 1
    fi

    if ! entry="$(find_recovery_entry "${uuid}" "${path}")"; then
        echo "Failed to detect boot EFI entry" >&2
        return 1
    fi

    if ! efibootmgr -o "${order},${entry}" 1>/dev/null; then
        echo "Failed to append entry in boot order" >&2
        return 1
    fi

    return 0
}

function is_signing_needed() {
    local -i keys=0
    local status section

    if ! command -v sbctl &>/dev/null; then
        echo "sbctl is not installed, skipping signing..."
        return 1
    fi

    if ! status="$(sbctl status --json)"; then
        return 1
    fi

    if ! [[ "$status" =~ \"installed\"[[:space:]]*:[[:space:]]*true ]]; then
        echo "sbctl is not installed, skipping signing..."
        return 1
    fi

    if ! [[ "$status" =~ \"secure_boot\"[[:space:]]*:[[:space:]]*true ]]; then
        echo "Secure boot is not enabled, skipping signing..."
        return 1
    fi

    if ! [[ "$status" =~ \"setup_mode\"[[:space:]]*:[[:space:]]*false ]]; then
        echo "Setup mode is enrolled, skipping signing..."
        return 1
    fi

    while IFS= read -r line; do
        case "$line" in
            PK:|KEK:|DB:) section="${line%:}";;
            ' '*|$'\t'*)
                if [[ -n "$section" ]]; then
                    ((keys++))
                    section=
                fi
                ;;
            *) ;;
        esac
    done < <(sbctl list-enrolled-keys || true)

    if ((keys != 3)); then
        echo "No keys enrolled, skipping signing..."
        return 1
    fi

    return 0
}

function copy_image() {
    local src="${1}"
    local dest="${2}"

    if ! install -m644 "${src}" "${dest}.new"; then
        echo "Failed to copy cachyos-recovery ${src} in ESP partition" >&2
        return 1
    fi

    if ! mv -f "${dest}.new" "${dest}"; then
        echo "Failed to install cachyos-recovery ${src} image" >&2
        rm -f "${dest}.new"
        return 1
    fi

    return 0
}

function install_recovery_efi() {
    local source target esp cmdline tmp

    if ! esp="$(bootctl --print-esp-path 2>/dev/null)"; then
        echo "Failed to detect ESP partition, make sure it is mounted"
        return 1
    fi

    source="/usr/lib/cachyos-recovery/cachyos-recovery.efi"
    target="${esp}/EFI/Linux/cachyos-recovery.efi"

    if [[ ! -s "${source}" ]]; then
        echo "cachyos-recovery image not found, exit..." >&2
        return 1
    fi

    if [[ ! -d "${esp}/EFI/Linux" ]]; then
        mkdir -p "${esp}/EFI/Linux"
    fi

    # In case if package was upgraded due to pkgrel increase
    if ! cmp -s "$source" "$target"; then
        if ! copy_image "$source" "$target"; then
            echo "Failed to install cachyos-recovery image" >&2
            return 1
        fi

        if is_signing_needed; then
            if ! sbctl sign "${target}"; then
                echo "Failed to sign ${target}, UEFI Secure Boot may not accept it" >&2
            fi
        fi
    fi

    if ! mkdir -p "${target}.extra.d"; then
        echo "Failed to create addon directory for CachyOS recovery" >&2
        return 1
    fi

    if ! cmdline="$(generate_cmdline)" || [[ -z "$cmdline" ]]; then
        echo "Failed to generate recovery kernel command line" >&2
        return 1
    fi

    if ! tmp="$(mktemp -d -t addon.XXXXXX)"; then
        echo "Failed to create temp directory: ${tmp}"
        return 1
    fi

    if ! ukify build \
        --cmdline="${cmdline}" \
        --output="${tmp}/root.addon.efi"; then
        echo "Failed to generate command-line addon for CachyOS recovery image" >&2
        rm -rf "${tmp}"
        return 1
    fi

    if ! install -m644 "${tmp}/root.addon.efi" "${target}.extra.d/root.addon.efi.new"; then
        rm -rf "${tmp}"
        echo "Failed to copy cachyos-recovery root addon in ESP partition" >&2
        return 1
    fi

    rm -rf "${tmp}"

    if ! mv -f "${target}.extra.d/root.addon.efi.new" "${target}.extra.d/root.addon.efi"; then
        rm -f "${target}.extra.d/root.addon.efi.new"
        echo "Failed to install cachyos-recovery root addon" >&2
        return 1
    fi

    if is_signing_needed; then
        if ! sbctl sign "${target}.extra.d/root.addon.efi"; then
            echo "Failed to sign root addon, UEFI Secure Boot may not accept it" >&2
        fi
    fi

    # Add boot entry in Limine if it's used
    if command -v limine-entry-tool &>/dev/null && [[ -e "${esp}/EFI/limine/limine_x64.efi" ]]; then
        if ! limine-entry-tool --add-efi "CachyOS Recovery" "${target}" --overwrite --quiet; then
            echo "Failed to add boot entry in Limine, please do this manually" >&2
        fi
    fi

    target="${target#"${esp}"}"
    target="${target//\//\\}"

    if ! create_boot_entry "${target}" "${esp}"; then
        echo "Failed to create EFI boot entry" >&2
    fi

    return 0
}

function generate_grub_entry() {
    local initrd="${1}"
    local vmlinuz="${2}"
    local cmdline uuid fstype subvol=""

    if ! cmdline="$(generate_cmdline)" || [[ -z "$cmdline" ]]; then
        echo "Failed to generate recovery kernel command line" >&2
        return 1
    fi

    if ! uuid="$(findmnt -no UUID /)"; then
        echo "Failed to get UUID of root" >&2
        return 1
    fi

    if ! fstype="$(findmnt -no FSTYPE /)"; then
        echo "Failed to detect root fstype" >&2
        return 1
    fi

    [[ "$fstype" == "btrfs" ]] && subvol="/@"

    cat << EOF | install -Dm755 /dev/stdin /etc/grub.d/50-cachyos-recovery
#!/bin/sh
exec tail -n +3 \$0

# THIS ENTRY IS AUTO-GENERATED BY CACHYOS-RECOVERY, DO NOT TOUCH
menuentry 'CachyOS Recovery' --id=cachyos-recovery {
    load_video
    set gfxpayload=keep
    search --no-floppy --fs-uuid --set=root ${uuid}
    linux ${subvol}${vmlinuz} ${cmdline}
    initrd ${subvol}${initrd}
}
EOF

    if ! grub-mkconfig -o /boot/grub/grub.cfg; then
        echo "Failed to regenerate GRUB config" >&2
        return 1
    fi

    return 0
}

function install_recovery_bios() {
    local initrd vmlinuz

    initrd="/usr/lib/cachyos-recovery/cachyos-recovery.initrd"
    vmlinuz="/usr/lib/cachyos-recovery/cachyos-recovery.vmlinuz"

    if ! [[ -s "$initrd"  && -s "$vmlinuz" ]]; then
        echo "Failed to find initrd images" >&2
        return 1
    fi

    target_initrd="/boot/${vmlinuz##*/}"
    target_vmlinuz="/boot/${initrd##*/}"

    if command -v limine-entry-tool &>/dev/null && [[ -s "/boot/limine-bios.sys" ]]; then
        if ! limine-entry-tool --add-kernel "cachyos-recovery" "${vmlinuz}" "${initrd}" \
            --comment "CachyOS Recovery" --quiet; then
            echo "Failed to install boot entry in Limine, please do this manually" >&2
            return 1
        fi
    else
        if ! cmp -s "$vmlinuz" "$target_vmlinuz"; then
            copy_image "$vmlinuz" "$target_vmlinuz" || false
        fi

        if ! cmp -s "$initrd" "$target_initrd"; then
            copy_image "$initrd" "$target_initrd" || false
        fi
    fi

    if [[ -d /etc/grub.d && -d /boot/grub/i386-pc ]]; then
        generate_grub_entry "$target_initrd" "$target_vmlinuz" || false
    fi

    return 0
}


if [[ -d /sys/firmware/efi/efivars ]]; then
    install_recovery_efi
else
    install_recovery_bios
fi
