#!/usr/bin/bash
# lamboot-migrate — BIOS→UEFI migration and cross-bootloader migration.
#
# The first automated end-to-end BIOS→UEFI migration tool for Linux.
# Handles: MBR→GPT conversion, ESP creation, bootloader installation,
# fstab rewrite, UEFI boot entry creation, verification, and rollback.
#
# Subcommands:
#   to-uefi [OPTIONS]    Convert BIOS/MBR system to UEFI/GPT (10-phase pipeline)
#   to-lamboot [OPTIONS] Migrate UEFI system from competing bootloader to LamBoot
#   verify [OPTIONS]     Run 12-check post-conversion verification
#   rollback [OPTIONS]   Revert the most recent to-uefi run using backup dir
#   status               Show current boot configuration
#
# Governed by ~/lamboot-dev/docs/specs/SPEC-LAMBOOT-MIGRATE.md (SDS-7).
# Part of the lamboot-tools suite; see SPEC-LAMBOOT-TOOLKIT-V1.md §3.1.

# shellcheck source=../lib/lamboot-toolkit-lib.sh
source "${LAMBOOT_LIB_DIR:-/usr/lib/lamboot-tools}/lamboot-toolkit-lib.sh"
# shellcheck source=../lib/lamboot-toolkit-help.sh
source "${LAMBOOT_LIB_DIR:-/usr/lib/lamboot-tools}/lamboot-toolkit-help.sh"

LAMBOOT_TOOL_NAME="lamboot-migrate"
LAMBOOT_TOOL_VERSION="0.7.6"

# ── Tool-specific options ────────────────────────────────────────────────
OPT_SUBCOMMAND=""
OPT_DISK=""
OPT_ESP_SIZE_MB=550
OPT_BOOTLOADER="grub-efi"
OPT_CMDLINE=""
OPT_BACKUP_DIR=""
OPT_METHOD="auto"
OPT_SKIP_VERIFY=0
OPT_KEEP_LEGACY_MBR=1
OPT_PRESERVE_GRUB=1
OPT_REMOVE_GRUB=0
OPT_UNSIGNED=0                # to-lamboot: skip --signed (Secure Boot OFF testing)
OPT_VERIFY_ALL=0
OPT_CAPCHECK_GATE=0           # opt-in capcheck readiness audit in preflight
OPT_VERIFY_PATH=""

# ── Phase 1 → Phase 5 shrink handoff (SDS-7 §3 Phase 5 shrink-to-make-room) ──
# Phase 1's guard_disk_free_space sets these when it determines the last
# partition must be shrunk to free space for the ESP. Phase 5 reads them to
# perform the actual resize2fs + sgdisk delete/recreate. Empty = no shrink.
LAMBOOT_NEEDS_SHRINK=0
LAMBOOT_SHRINK_LAST_PART_NUM=""
LAMBOOT_SHRINK_LAST_PART_DEV=""
LAMBOOT_SHRINK_NEW_PART_MB=""
LAMBOOT_SHRINK_DONE=0           # set to 1 by Phase 3b after shrink completes

# ── Method B chroot orchestration (SDS-7 §4.2 — runs under live ISO) ──
# Method B converts a target disk while booted from live media. Phase 5b mounts
# the target's (shrunken) root + the new ESP under LAMBOOT_TARGET_ROOT so that
# Phases 6-10 operate on the *target's* /etc/fstab, /boot, /boot/efi rather
# than the live ISO's. Method A leaves LAMBOOT_TARGET_ROOT empty so the
# helpers degrade to identity / no-op.
LAMBOOT_TARGET_ROOT=""
LAMBOOT_TARGET_BINDS=()
# Separate target filesystems (a dedicated /boot, /usr, … declared in the
# target's fstab) mounted under LAMBOOT_TARGET_ROOT in Phase 5b, shallow→deep.
# Without these the chroot's /boot is an empty mountpoint and grub-mkconfig
# emits a kernel-less grub.cfg (SDS-7 separate-/boot defect — see archie).
LAMBOOT_TARGET_FS_MOUNTS=()

# ── Inter-phase return-value globals ─────────────────────────────────────
# Bash function "returns" via stdout (`$(...)` capture) get corrupted when
# the function also invokes external commands that write to stdout. Use
# named globals instead for inter-phase data passing.
LAMBOOT_PHASE5_ESP_DEV=""

# ── Help registry (§10, three-surface rendering) ─────────────────────────
_register_subcommands() {
    register_subcommand \
        --name "to-uefi" \
        --category "Migration" \
        --summary "Convert BIOS/MBR system to UEFI/GPT" \
        --syntax "lamboot-migrate to-uefi [--disk DEV] [--esp-size MB] [--bootloader NAME] [--method A|B|C|auto] [--cmdline STR] [--backup-dir PATH] [--skip-verify] [--keep-legacy-mbr]" \
        --arg "--disk DEV:Target disk (default: auto-detect root disk)" \
        --arg "--esp-size MB:ESP partition size in MB (default: 550)" \
        --arg "--bootloader NAME:grub-efi (default), lamboot, or systemd-boot" \
        --arg "--method A|B|C|auto:Proxmox VM method selector (default: auto)" \
        --arg "--cmdline STR:Override kernel cmdline for new BLS entries" \
        --arg "--backup-dir PATH:Where to store the backup (default: /var/backups/lamboot-migrate-<ts>/)" \
        --arg "--skip-verify:Don't run verification suite after conversion" \
        --arg "--keep-legacy-mbr:Leave MBR boot code (protective) — default" \
        --example "sudo lamboot-migrate to-uefi --disk /dev/sda" \
        --example "sudo lamboot-migrate to-uefi --dry-run" \
        --example "sudo lamboot-migrate to-uefi --bootloader lamboot --esp-size 1024" \
        --notes "Runs a 10-phase pipeline with safety gates at each step. The first 6 phases are reversible with no disk changes (rollback runs a diff). After Phase 4 (MBR→GPT), rollback requires the backup dir. Always back up your system before running. For boot disk migration on physical hardware, run from live media." \
        --offline-capable "false" \
        --requires-root "true" \
        --see-also "to-lamboot, verify, rollback, status" \
        --doc-url "https://github.com/lamco-admin/lamboot-tools" \
        --maturity "stable"

    register_subcommand \
        --name "to-lamboot" \
        --category "Migration" \
        --summary "Migrate UEFI system from another bootloader to LamBoot" \
        --syntax "lamboot-migrate to-lamboot [--esp PATH] [--preserve-grub|--remove-grub] [--unsigned] [--force]" \
        --arg "--esp PATH:ESP mount point (default: auto-detect)" \
        --arg "--preserve-grub:Keep existing bootloader as fallback (default)" \
        --arg "--remove-grub:Remove GRUB packages + ESP files + NVRAM entries after verify passes (DANGEROUS)" \
        --arg "--unsigned:Install the unsigned LamBoot binary (Secure Boot OFF systems). Default is --signed for SB compatibility." \
        --arg "--force:Skip typed-yes confirmation when --remove-grub is used" \
        --example "sudo lamboot-migrate to-lamboot" \
        --example "sudo lamboot-migrate to-lamboot --preserve-grub" \
        --example "sudo lamboot-migrate to-lamboot --unsigned    # SB-off systems" \
        --example "sudo lamboot-migrate to-lamboot --remove-grub    # asks for confirmation" \
        --example "sudo lamboot-migrate to-lamboot --remove-grub --force" \
        --notes "Invokes lamboot-install. Default is --signed (Secure Boot path: lambootx64-signed.efi shipped from /usr/share/lamboot/). Pass --unsigned to install the unsigned binary on SB-off systems (must still be installed from /usr/share/lamboot/ but lamboot-install will use lambootx64.efi instead). With --preserve-grub (default) the prior bootloader stays as a UEFI fallback. With --remove-grub the tool runs verify first; if all 12 checks pass, it uninstalls the distro's GRUB packages, removes GRUB files from the ESP, and deletes GRUB Boot#### entries from NVRAM. Refuses to remove if verify fails. Requires typed-yes confirmation unless --force." \
        --offline-capable "false" \
        --requires-root "true" \
        --see-also "to-uefi, rollback" \
        --doc-url "https://github.com/lamco-admin/lamboot-tools" \
        --maturity "stable"

    register_subcommand \
        --name "verify" \
        --category "Verification" \
        --summary "Run the 12-check post-conversion verification suite" \
        --syntax "lamboot-migrate verify [--all] [--path BACKUP-DIR] [--json]" \
        --arg "--all:Run all checks (default)" \
        --arg "--path PATH:Verify a backup directory produced by --backup-dir" \
        --example "sudo lamboot-migrate verify" \
        --example "sudo lamboot-migrate verify --json" \
        --example "sudo lamboot-migrate verify --path /var/backups/lamboot-migrate-2026-04-22..." \
        --notes "Runs 11 independent checks per SDS-7 §9. Exits 0 if all pass, 1 if any fail. Safe to run repeatedly. Read-only — does not modify state." \
        --offline-capable "false" \
        --requires-root "false" \
        --see-also "to-uefi, rollback" \
        --doc-url "https://github.com/lamco-admin/lamboot-tools" \
        --maturity "stable"

    register_subcommand \
        --name "rollback" \
        --category "Recovery" \
        --summary "Revert the most recent to-uefi run using its backup" \
        --syntax "lamboot-migrate rollback [--backup-dir PATH]" \
        --arg "--backup-dir PATH:Specific backup to restore (default: most recent)" \
        --example "sudo lamboot-migrate rollback" \
        --example "sudo lamboot-migrate rollback --backup-dir /var/backups/lamboot-migrate-2026-04-22..." \
        --example "sudo lamboot-migrate rollback --dry-run" \
        --notes "Restores the original MBR partition table, original fstab, and original /etc/default/grub. Removes the UEFI boot entry created during to-uefi. You will need to switch firmware back to Legacy/CSM after rollback to boot off the restored MBR." \
        --offline-capable "false" \
        --requires-root "true" \
        --see-also "to-uefi, verify" \
        --doc-url "https://github.com/lamco-admin/lamboot-tools" \
        --maturity "stable"

    register_subcommand \
        --name "status" \
        --category "Information" \
        --summary "Show current boot configuration and migration readiness" \
        --syntax "lamboot-migrate status [--json]" \
        --example "lamboot-migrate status" \
        --example "lamboot-migrate status --json | jq .findings" \
        --notes "Read-only; runs unprivileged. Reports boot mode, partition table type, ESP state, installed bootloaders, fstab form, and migration readiness." \
        --offline-capable "false" \
        --requires-root "false" \
        --see-also "to-uefi, verify" \
        --doc-url "https://github.com/lamco-admin/lamboot-tools" \
        --maturity "stable"
}

# ── Phase 1 preflight guardrails (SDS-7 §5) ──────────────────────────────

guard_boot_mode_is_bios() {
    # Method B converts a BIOS *target* disk while booted from a UEFI live ISO.
    # The live environment's own UEFI firmware (/sys/firmware/efi present) is
    # REQUIRED for Method B — it must not be mistaken for "the running system is
    # already UEFI, nothing to do". Only the in-place path (Method A / auto on
    # the running system, where the running system IS the target) treats a UEFI
    # /sys/firmware/efi as a no-op.
    if [[ "$OPT_METHOD" == "B" ]]; then
        return 0
    fi
    if [[ -d /sys/firmware/efi ]]; then
        emit_finding "migrate.boot_mode.already_uefi" "firmware" "info" "pass" \
            "System is already UEFI" \
            "No BIOS→UEFI conversion needed; boot mode is UEFI." \
            "{}" '{"summary":"Run lamboot-migrate to-lamboot if you want to switch to LamBoot","command":"lamboot-migrate to-lamboot","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
        die_noop "system is already UEFI"
    fi
}

guard_required_tools() {
    local missing=()
    for tool in sgdisk sfdisk mkfs.vfat efibootmgr blkid lsblk findmnt rsync dumpe2fs resize2fs e2fsck; do
        command -v "$tool" >/dev/null 2>&1 || missing+=("$tool")
    done
    if [[ ${#missing[@]} -gt 0 ]]; then
        emit_finding "migrate.preflight.tools_missing" "preflight" "critical" "fail" \
            "Required tools not found" \
            "Missing: ${missing[*]}. Install gdisk + dosfstools + efibootmgr + util-linux." \
            "{\"missing\":[\"$(printf '%s' "${missing[*]}" | sed 's/ /","/g')\"]}" \
            '{"summary":"Install required tools via your package manager","command":"sudo apt install gdisk dosfstools efibootmgr || sudo dnf install gdisk dosfstools efibootmgr","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
        die_prerequisite "required tools missing: ${missing[*]}"
    fi
}

guard_root_not_on_lvm_or_crypt() {
    local root_source
    root_source=$(findmnt -n -o SOURCE / 2>/dev/null | sed 's/\[.*\]//')

    if [[ "$root_source" == /dev/mapper/* ]]; then
        # `cryptsetup status` exits 0 for ANY active device-mapper node — an LVM
        # LV included — printing "type: n/a" for non-crypt. Confirm a real crypt
        # mapping (LUKS/PLAIN) so an LVM root is not misreported as encrypted;
        # otherwise this branch shadows the LVM check below for every LVM root
        # (observed on RHEL 9.7: XFS-root-on-LVM reported as dm-crypt).
        if command -v cryptsetup >/dev/null 2>&1 \
            && cryptsetup status "$(basename "$root_source")" 2>/dev/null \
                | grep -qiE '^[[:space:]]*type:[[:space:]]*(LUKS|PLAIN)'; then
            emit_finding "migrate.preflight.encrypted_root" "preflight" "critical" "fail" \
                "Root filesystem is on dm-crypt" \
                "Encrypted-root BIOS→UEFI migration is not automated in v1.0 (too much risk)." \
                "{}" \
                '{"summary":"Manual migration path — see documentation","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
            die_unsafe "root on dm-crypt — automated conversion refused"
        fi

        if command -v lvdisplay >/dev/null 2>&1 && lvdisplay "$root_source" >/dev/null 2>&1; then
            emit_finding "migrate.preflight.lvm_root" "preflight" "critical" "fail" \
                "Root filesystem is on LVM" \
                "LVM-root BIOS→UEFI migration is not automated in v1.0." \
                "{}" \
                '{"summary":"Manual migration path — see documentation","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
            die_unsafe "root on LVM — automated conversion refused"
        fi
    fi
}

guard_no_hybrid_mbr() {
    local disk="$1"
    # Canonical sgdisk flag is --print-mbr (short -O). Output is a header
    # plus a "Number Boot Start ... Code" table; MBR partition rows start
    # with optional-whitespace digits. A hybrid is GPT + >1 MBR entry,
    # because entry 1 is the GPT protective partition (0xEE) and any
    # additional entry is a non-protective overlay — exactly what Rod
    # Smith calls "flaky and dangerous" in hybrid.html.
    local mbr_output
    mbr_output=$(sgdisk --print-mbr "$disk" 2>/dev/null || true)
    local mbr_partitions
    mbr_partitions=$(printf '%s' "$mbr_output" | grep -cE '^\s*[0-9]+\s' || true)
    mbr_partitions="${mbr_partitions:-0}"

    local pttype
    pttype=$(blkid -o value -s PTTYPE "$disk" 2>/dev/null || true)

    if [[ "$pttype" == "gpt" ]] && [[ "$mbr_partitions" -gt 1 ]]; then
        emit_finding "migrate.preflight.hybrid_mbr" "preflight" "critical" "fail" \
            "Hybrid MBR detected" \
            "The disk has both GPT and non-protective MBR partitions. Rod Smith calls hybrid MBRs 'flaky and dangerous.'" \
            "{\"disk\":\"$(json_escape "$disk")\",\"mbr_partition_count\":${mbr_partitions}}" \
            '{"summary":"Manual cleanup required","doc_url":"https://www.rodsbooks.com/gdisk/hybrid.html"}'
        die_unsafe "hybrid MBR detected on $disk — refusing automated conversion"
    fi
}

guard_no_windows() {
    local disk="$1"

    # Two-tier detection. blkid/lsblk catches a functioning NTFS via BPB
    # inspection (primary path). A partition-type-code check via sfdisk
    # catches the case where blkid can't parse the NTFS (corrupted, fake,
    # or very small install) — Windows MBR uses 0x07 (HPFS/NTFS/exFAT) or
    # 0x27 (hidden). Per SDS-7 §5.7 we refuse on either signal to keep
    # the safety-first posture.
    local parts
    parts=$(lsblk -nr -o NAME,FSTYPE "$disk" 2>/dev/null || true)
    local ntfs_via_lsblk=0
    if printf '%s' "$parts" | awk '{print $2}' | grep -qi 'ntfs'; then
        ntfs_via_lsblk=1
    fi

    local ntfs_via_type=0
    if command -v sfdisk >/dev/null 2>&1; then
        # sfdisk renders the MBR type code without leading zeros or 0x
        # prefix (e.g. "type=7" for 0x07, "type=27" for 0x27). Match all
        # plausible forms so we're robust across sfdisk versions.
        if sfdisk -d "$disk" 2>/dev/null | grep -qE 'type=(0x)?0?(7|27)\b'; then
            ntfs_via_type=1
        fi
    fi

    if [[ $ntfs_via_lsblk -eq 1 ]] || [[ $ntfs_via_type -eq 1 ]]; then
        local ntfs_part
        ntfs_part=$(printf '%s' "$parts" | awk '$2 ~ /ntfs|NTFS/ {print $1; exit}')
        local bmgr=""
        if [[ -n "$ntfs_part" ]]; then
            local mp
            mp=$(mktemp -d -t lamboot-migrate-check.XXXXXX)
            if mount -o ro,noexec,nodev "/dev/$ntfs_part" "$mp" 2>/dev/null; then
                [[ -d "$mp/Windows/Boot" ]] && bmgr="detected"
                umount "$mp" 2>/dev/null || true
            fi
            rmdir "$mp" 2>/dev/null || true
        fi

        # Confidence levels:
        #   bmgr="detected"   → /Windows/Boot dir found, definitive Windows install
        #   ntfs_via_type=1   → MBR type 0x07/0x27, strong signal of Windows intent
        #                       even if the NTFS is damaged or uninitialized
        # Either fires die_unsafe per SDS-7 §5.7 safety-first posture.
        if [[ "$bmgr" == "detected" ]] || [[ $ntfs_via_type -eq 1 ]]; then
            local detail="Windows install detected on target disk"
            [[ "$bmgr" != "detected" ]] && detail="Windows-typed partition detected on target disk (MBR type 0x07/0x27)"
            emit_finding "migrate.preflight.windows_present" "preflight" "critical" "fail" \
                "$detail" \
                "Windows dual-boot with MBR→GPT conversion requires BCD rewriting, not automated in v1.0." \
                "{\"disk\":\"$(json_escape "$disk")\",\"ntfs_partition\":\"$(json_escape "${ntfs_part:-unknown}")\",\"detection\":\"${bmgr:-partition-type}\"}" \
                '{"summary":"Manual dual-boot migration","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
            die_unsafe "Windows present on $disk — refusing automated conversion"
        fi
    fi
}

guard_fstab_uuid_form() {
    local dev_entries
    dev_entries=$(grep -cE '^\s*/dev/sd[a-z]|^\s*/dev/nvme|^\s*/dev/hd[a-z]' /etc/fstab 2>/dev/null || true)
    dev_entries="${dev_entries:-0}"

    if [[ "$dev_entries" -gt 0 ]]; then
        emit_finding "migrate.preflight.fstab_device_paths" "preflight" "warning" "warn" \
            "fstab contains device-path entries" \
            "${dev_entries} fstab entries use /dev/ paths. These may break after MBR→GPT conversion. Phase 6 will rewrite them to UUID= form." \
            "{\"count\":${dev_entries}}" \
            '{"summary":"Phase 6 rewrites automatically; nothing to do","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
    fi
}

# Returns: MB the ext4 on $1 can be safely shrunk by (printed to stdout),
# or 0 if not ext4 / unreadable. Reads superblock via dumpe2fs -h (read-only,
# works on mounted FS); applies a 10% headroom margin so we never push the FS
# to its absolute minimum. Used by guard_disk_free_space + Phase 5 shrink.
ext4_shrinkable_mb() {
    local dev="$1"
    [[ -b "$dev" ]] || { printf '0'; return 0; }

    local fstype
    fstype=$(blkid -o value -s TYPE "$dev" 2>/dev/null || true)
    [[ "$fstype" == "ext4" ]] || { printf '0'; return 0; }

    local sb block_size block_count free_blocks
    sb=$(dumpe2fs -h "$dev" 2>/dev/null) || { printf '0'; return 0; }
    block_size=$(awk -F: '/^Block size:/ {gsub(/ /,"",$2); print $2}' <<<"$sb")
    block_count=$(awk -F: '/^Block count:/ {gsub(/ /,"",$2); print $2}' <<<"$sb")
    free_blocks=$(awk -F: '/^Free blocks:/ {gsub(/ /,"",$2); print $2}' <<<"$sb")

    [[ "$block_size" =~ ^[0-9]+$ && "$free_blocks" =~ ^[0-9]+$ && "$block_count" =~ ^[0-9]+$ ]] \
        || { printf '0'; return 0; }

    # 90% of free space, converted to MB (integer math).
    printf '%s' $(( free_blocks * block_size * 9 / 10 / 1024 / 1024 ))
}

guard_disk_free_space() {
    local disk="$1"
    local need_mb="$2"
    local size_sectors last_sector
    size_sectors=$(blockdev --getsz "$disk" 2>/dev/null || printf '0')
    last_sector=$(sgdisk -p "$disk" 2>/dev/null | tail -1 | awk '{print $3}' || printf '0')
    last_sector="${last_sector:-0}"
    # On a partition-table-less or empty disk, `sgdisk -p` ends with the
    # column-header line `Number Start (sector) End (sector)...`, so
    # `tail -1 | awk '{print $3}'` yields the literal "(sector)" rather
    # than a number. Sanitize to 0 (treat-as-empty) so the size check
    # below doesn't trip `set -u` on a non-numeric arithmetic operand.
    [[ "$last_sector" =~ ^[0-9]+$ ]] || last_sector=0

    if [[ "$size_sectors" == "0" ]] || [[ "$last_sector" == "0" ]]; then
        verbose "disk space check inconclusive — will attempt creation anyway"
        return 0
    fi

    local free_sectors=$((size_sectors - last_sector))
    local free_mb=$((free_sectors * 512 / 1024 / 1024))

    # Path A: there is already enough unallocated space at the end. Done.
    if [[ "$free_mb" -ge "$need_mb" ]]; then
        return 0
    fi

    # Path B: not enough unallocated. Can we make room by shrinking the
    # last partition (per SDS-7 §3 Phase 5)? Identify the last partition
    # by start sector, check if its filesystem is shrinkable ext4.
    local last_part_num last_part_dev last_part_fstype start_sector
    last_part_num=$(sgdisk -p "$disk" 2>/dev/null \
        | awk '$1 ~ /^[0-9]+$/ {print $1, $2}' \
        | sort -k2 -n | tail -1 | awk '{print $1}')
    if [[ -n "$last_part_num" ]]; then
        last_part_dev=$(partition_device_for "$disk" "$last_part_num")
        last_part_fstype=$(blkid -o value -s TYPE "$last_part_dev" 2>/dev/null || true)
        start_sector=$(sgdisk -p "$disk" 2>/dev/null \
            | awk -v n="$last_part_num" '$1 == n {print $2}')
    fi

    local shrinkable_mb=0
    if [[ "$last_part_fstype" == "ext4" ]]; then
        shrinkable_mb=$(ext4_shrinkable_mb "$last_part_dev")
    fi

    # Need ESP size + 64 MB margin for alignment/GPT-end-backup
    local need_buffer=$((need_mb + 64))
    if [[ "$shrinkable_mb" -ge "$need_buffer" ]] && [[ -n "$start_sector" ]]; then
        # Compute target partition size: current_size_mb - need_mb - 32 MB safety
        local part_size_mb new_part_mb
        part_size_mb=$(( (last_sector - start_sector + 1) * 512 / 1024 / 1024 ))
        new_part_mb=$(( part_size_mb - need_mb - 32 ))

        LAMBOOT_NEEDS_SHRINK=1
        LAMBOOT_SHRINK_LAST_PART_NUM="$last_part_num"
        LAMBOOT_SHRINK_LAST_PART_DEV="$last_part_dev"
        LAMBOOT_SHRINK_NEW_PART_MB="$new_part_mb"

        emit_finding "migrate.preflight.shrink_required" "preflight" "warning" "warn" \
            "Will shrink last partition to make room for ESP" \
            "No unallocated space at end of $disk; Phase 3b will shrink ${last_part_dev} (ext4, ~${shrinkable_mb} MB shrinkable) from ${part_size_mb} MB to ${new_part_mb} MB to free ${need_mb} MB for the ESP." \
            "{\"disk\":\"$(json_escape "$disk")\",\"shrink_part\":\"$(json_escape "$last_part_dev")\",\"shrinkable_mb\":${shrinkable_mb},\"need_mb\":${need_mb},\"current_mb\":${part_size_mb},\"new_part_mb\":${new_part_mb}}" \
            '{"summary":"Phase 3b will resize2fs + sfdisk shrink before MBR→GPT","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
        warn "no unallocated space; Phase 3b will shrink $last_part_dev to ${new_part_mb} MB (was ${part_size_mb} MB)"
        return 0
    fi

    # Path C: neither unallocated nor shrinkable. Fail.
    emit_finding "migrate.preflight.insufficient_free_space" "preflight" "error" "fail" \
        "Insufficient free space at end of disk" \
        "Need ${need_mb} MB for ESP; ${free_mb} MB unallocated, ${shrinkable_mb} MB shrinkable from last partition (${last_part_dev:-none}, ${last_part_fstype:-unknown})." \
        "{\"disk\":\"$(json_escape "$disk")\",\"free_mb\":${free_mb},\"shrinkable_mb\":${shrinkable_mb},\"need_mb\":${need_mb}}" \
        '{"summary":"Use a smaller --esp-size or attach a second disk","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'

    if [[ $LAMBOOT_FORCE -eq 0 ]]; then
        die "insufficient free space for ESP ($free_mb MB free, $shrinkable_mb MB shrinkable, need $need_mb MB)"
    fi
    warn "continuing despite insufficient space (--force)"
}

guard_existing_esp_collision() {
    local disk="$1"
    local existing_esp
    existing_esp=$(sgdisk -p "$disk" 2>/dev/null | awk '$6 == "EF00" {print $1}' | head -1 || true)
    if [[ -n "$existing_esp" ]]; then
        verbose "existing ESP on $disk at partition $existing_esp — will reuse"
    fi
    printf '%s' "$existing_esp"
}

# ── Disk + partition utilities ───────────────────────────────────────────

partition_device_for() {
    local disk="$1"
    local partnum="$2"
    if [[ "$disk" =~ nvme|mmcblk|loop ]]; then
        printf '%sp%s' "$disk" "$partnum"
    else
        printf '%s%s' "$disk" "$partnum"
    fi
}

# target_path PATH — prepend LAMBOOT_TARGET_ROOT to PATH when running under
# Method B; return PATH unchanged when Method A (LAMBOOT_TARGET_ROOT empty).
# Used by phases that read/write files which MUST belong to the target system
# (e.g. /etc/fstab, /etc/default/grub), not the live ISO's copies.
target_path() {
    if [[ -n "$LAMBOOT_TARGET_ROOT" ]]; then
        printf '%s%s' "$LAMBOOT_TARGET_ROOT" "$1"
    else
        printf '%s' "$1"
    fi
}

# target_run CMD... — run CMD inside the target chroot under Method B,
# or directly in the live env under Method A. Wraps lamboot_run so --dry-run
# still prints the planned command. Used by phases that invoke the target's
# package manager / bootloader installer (grub-install must run under the
# target's rootfs to find the right packages + kernel images).
target_run() {
    if [[ -n "$LAMBOOT_TARGET_ROOT" ]]; then
        lamboot_run chroot "$LAMBOOT_TARGET_ROOT" "$@"
    else
        lamboot_run "$@"
    fi
}

# cleanup_target_mounts — unmount everything Phase 5b + Phase 7 mounted into
# LAMBOOT_TARGET_ROOT. Wired to EXIT trap by do_to_uefi so the live ISO is
# left clean even on Phase 6-10 failure. Idempotent + survives partial setup.
cleanup_target_mounts() {
    [[ -z "$LAMBOOT_TARGET_ROOT" ]] && return 0
    local bind
    # Unmount binds in reverse order (LIFO)
    local i
    for (( i=${#LAMBOOT_TARGET_BINDS[@]}-1; i>=0; i-- )); do
        bind="${LAMBOOT_TARGET_BINDS[$i]}"
        umount "$bind" 2>/dev/null || umount -l "$bind" 2>/dev/null || true
    done
    LAMBOOT_TARGET_BINDS=()
    umount "$LAMBOOT_TARGET_ROOT/boot/efi" 2>/dev/null || true
    # Separate target filesystems (e.g. a dedicated /boot), deepest-first so a
    # parent isn't unmounted while a child is still mounted on it.
    local j
    for (( j=${#LAMBOOT_TARGET_FS_MOUNTS[@]}-1; j>=0; j-- )); do
        umount "${LAMBOOT_TARGET_FS_MOUNTS[$j]}" 2>/dev/null \
            || umount -l "${LAMBOOT_TARGET_FS_MOUNTS[$j]}" 2>/dev/null || true
    done
    LAMBOOT_TARGET_FS_MOUNTS=()
    umount "$LAMBOOT_TARGET_ROOT" 2>/dev/null || true
}

# resolve_fstab_spec_for_mountpoint FSTAB MOUNTPOINT — map a target fstab entry
# to a current block device. UUID/PARTUUID/LABEL are filesystem-stable across
# MBR→GPT (partitions are not reformatted), so blkid resolves them; a /dev/sdaN
# spec keeps its partition NUMBER under `sgdisk --mbrtogpt`, so it is remapped
# onto OPT_DISK. Prints the device on success; non-zero + no output otherwise.
resolve_fstab_spec_for_mountpoint() {
    local fstab="$1" want="$2" spec mp rest dev=""
    while read -r spec mp rest; do
        [[ "$mp" == "$want" ]] || continue
        case "$spec" in
            UUID=*)     dev=$(blkid -U "${spec#UUID=}" 2>/dev/null || true) ;;
            PARTUUID=*) dev=$(blkid -t "PARTUUID=${spec#PARTUUID=}" -o device 2>/dev/null | head -1 || true) ;;
            LABEL=*)    dev=$(blkid -L "${spec#LABEL=}" 2>/dev/null || true) ;;
            /dev/*)
                local n="${spec##*[!0-9]}"
                if [[ -n "$n" ]]; then dev=$(partition_device_for "$OPT_DISK" "$n"); else dev="$spec"; fi
                ;;
        esac
        [[ -n "$dev" && -b "$dev" ]] && { printf '%s' "$dev"; return 0; }
        return 1
    done < "$fstab"
    return 1
}

# mount_target_separate_filesystems — mount every separate block filesystem the
# target declares in its fstab (most importantly a dedicated /boot, but also a
# split /usr or /var) under LAMBOOT_TARGET_ROOT before Phase 8 runs grub-install
# / grub-mkconfig. Skips root and /boot/efi (mounted explicitly elsewhere) and
# non-block pseudo filesystems. Mounts shallow→deep so parents precede children.
# This is the SDS-7 separate-/boot fix: without it the chroot's /boot is empty,
# grub-mkconfig finds no kernel, and the migrated disk is unbootable.
mount_target_separate_filesystems() {
    local fstab="$LAMBOOT_TARGET_ROOT/etc/fstab"
    [[ -f "$fstab" ]] || return 0

    local -a candidates=()
    local spec mp fstype rest
    while read -r spec mp fstype rest; do
        [[ -z "$spec" || "$spec" == \#* ]] && continue
        case "$mp" in /|/boot/efi|none|swap|"") continue ;; esac
        case "$fstype" in swap|proc|sysfs|tmpfs|devpts|devtmpfs|none|"") continue ;; esac
        case "$spec" in UUID=*|PARTUUID=*|LABEL=*|/dev/*) ;; *) continue ;; esac
        candidates+=("$mp")
    done < "$fstab"
    [[ ${#candidates[@]} -eq 0 ]] && return 0

    # Sort by path depth (number of slashes) so /boot mounts before /boot/foo.
    local sorted m dev
    sorted=$(printf '%s\n' "${candidates[@]}" | awk '{print gsub(/\//,"/"), $0}' | sort -n | cut -d' ' -f2-)
    while IFS= read -r m; do
        [[ -z "$m" ]] && continue
        if ! dev=$(resolve_fstab_spec_for_mountpoint "$fstab" "$m"); then
            warn "could not resolve target device for $m; skipping (chroot may be incomplete)"
            continue
        fi
        lamboot_run mkdir -p "${LAMBOOT_TARGET_ROOT}${m}"
        if lamboot_run mount "$dev" "${LAMBOOT_TARGET_ROOT}${m}"; then
            LAMBOOT_TARGET_FS_MOUNTS+=("${LAMBOOT_TARGET_ROOT}${m}")
            record_action "method_b.mount.separate_fs" "$dev" "ok" "false" \
                "{\"mountpoint\":\"$(json_escape "${LAMBOOT_TARGET_ROOT}${m}")\"}" "null"
            verbose "mounted separate target filesystem $m ($dev)"
        else
            warn "failed to mount separate target filesystem $m ($dev)"
        fi
    done <<< "$sorted"
}

detect_target_disk() {
    if [[ -n "$OPT_DISK" ]]; then
        printf '%s' "$OPT_DISK"
        return 0
    fi
    local root_source
    root_source=$(findmnt -n -o SOURCE / 2>/dev/null | sed 's/\[.*\]//' || true)
    [[ -z "$root_source" ]] && return 1
    local parent
    parent=$(lsblk -nro PKNAME "$root_source" 2>/dev/null | head -1 || true)
    [[ -z "$parent" ]] && return 1
    printf '/dev/%s' "$parent"
}

# ── Proxmox method detection + pre-checks (SDS-7 §4) ────────────────────
#
# Three methods for BIOS→UEFI conversion of a Proxmox VM:
#
#   A = pre-convert (preferred): running inside the VM, convert in place.
#       Requires ≥ ESP_SIZE_MB free on the root disk OR adjacent unallocated.
#   B = post-convert live chroot: booted from a live ISO, converting the
#       target disk that's mounted at /mnt/sysroot (or similar). Phase 7
#       bind-mounts /dev /proc /sys /sys/firmware/efi into the chroot.
#   C = add-disk: attach a small second disk as the ESP-carrier; leave the
#       root disk MBR. Cosmetically unusual but zero-risk to root. Requires
#       a second block device to be already attached and empty.
#
# On physical hosts, only Method A applies. B/C are VM-specific.

_detect_running_in_proxmox_vm() {
    # DMI strings that QEMU/KVM VMs under Proxmox carry in their firmware.
    # /sys/class/dmi/id/sys_vendor is "QEMU"; product_name is often
    # "Standard PC" or similar. A real Proxmox VM has both + virtio devs.
    local vendor="" product=""
    [[ -r /sys/class/dmi/id/sys_vendor ]] && vendor=$(tr -d '\n' < /sys/class/dmi/id/sys_vendor 2>/dev/null)
    [[ -r /sys/class/dmi/id/product_name ]] && product=$(tr -d '\n' < /sys/class/dmi/id/product_name 2>/dev/null)
    [[ "$vendor" == "QEMU" ]] || [[ "$product" == *QEMU* ]]
}

_detect_running_from_live_media() {
    # Common live-media markers: overlay rootfs, /run/initramfs populated,
    # or kernel cmdline mentioning boot=live / live media identifiers.
    local rootfs
    rootfs=$(findmnt -n -o FSTYPE / 2>/dev/null || true)
    [[ "$rootfs" == "overlay" ]] && return 0
    [[ -d /run/initramfs/live ]] && return 0
    grep -qE 'boot=live|rd\.live\.image|live-media' /proc/cmdline 2>/dev/null && return 0
    return 1
}

_count_extra_block_disks() {
    # Count block devices that are not the target disk and not removable.
    # Used by Method C auto-detection — we want to see if a second disk
    # is available to become the ESP-carrier.
    local target="${OPT_DISK:-}"
    local count=0
    local dev
    while read -r dev; do
        [[ -z "$dev" ]] && continue
        [[ "/dev/$dev" == "$target" ]] && continue
        # Skip removable + read-only + zero-size
        local rm rossz
        rm=$(cat "/sys/block/$dev/removable" 2>/dev/null || echo 0)
        rossz=$(cat "/sys/block/$dev/size" 2>/dev/null || echo 0)
        [[ "$rm" == "0" ]] && [[ "$rossz" != "0" ]] && count=$((count + 1))
    done < <(lsblk -dn -o NAME 2>/dev/null | grep -E '^(sd|vd|nvme|xvd)' || true)
    printf '%d' "$count"
}

detect_proxmox_method() {
    case "$OPT_METHOD" in
        a|A) printf 'A'; return 0 ;;
        b|B) printf 'B'; return 0 ;;
        c|C) printf 'C'; return 0 ;;
        auto) ;;
        *) die "invalid --method: $OPT_METHOD (use auto, A, B, or C)" ;;
    esac

    # Auto-select per SDS-7 §4.4:
    #   1. Live-media present → B (user has clearly booted rescue/installer)
    #   2. Physical host or no Proxmox DMI → A (only method that applies)
    #   3. On a Proxmox VM: prefer A; if no free space, prefer C if a
    #      second disk is visible, else fall back to B.

    if _detect_running_from_live_media; then
        printf 'B'
        return 0
    fi

    if ! _detect_running_in_proxmox_vm; then
        printf 'A'
        return 0
    fi

    # We're in a Proxmox VM. Defer the free-space decision to Phase 1
    # (guard_disk_free_space has the authoritative math). If a second disk
    # is present, record that Method C is viable as a fallback; default
    # pick stays A and the guardrail will downgrade if needed.
    printf 'A'
}

# Method-specific pre-flight checks beyond the common guards. Called at
# the start of Phase 1 after the method is known, so we can diagnose
# "wrong method for this environment" before any mutation.
guard_method_prerequisites() {
    local method
    method=$(detect_proxmox_method)

    case "$method" in
        A)
            # Method A: in-place conversion. Already in the VM; no extra
            # pre-check beyond what Phase 1 runs (free-space, etc.).
            :
            ;;
        B)
            # Method B: we're in a live chroot. /sys/firmware/efi may or
            # may not be present (live USB may itself be UEFI or legacy).
            # We NEED a target root specified via --disk explicitly — we
            # can't auto-detect because findmnt / points at the live media,
            # not the target root.
            if [[ -z "$OPT_DISK" ]] || [[ "$OPT_DISK" == "/dev/null" ]]; then
                emit_finding "migrate.method_b.no_target_disk" "preflight" "critical" "fail" \
                    "Method B requires --disk targeting the VM's root disk" \
                    "When running from live media, findmnt / sees the live USB, not the install target. Specify --disk /dev/sdX explicitly." \
                    "{\"method\":\"B\"}" \
                    '{"summary":"Specify the target disk","command":"lamboot-migrate to-uefi --method B --disk /dev/sdX"}'
                die_unsafe "Method B requires explicit --disk"
            fi
            ;;
        C)
            # Method C: second disk as ESP-carrier. Root disk stays MBR.
            # Need a second block device visible + empty (no partition table).
            local extra
            extra=$(_count_extra_block_disks)
            if [[ "$extra" -lt 1 ]]; then
                emit_finding "migrate.method_c.no_second_disk" "preflight" "critical" "fail" \
                    "Method C requires a second block device as the ESP-carrier" \
                    "Attach a small (≥ 1 GB) second disk to the VM before running. From Proxmox: qm set <VMID> --scsi1 <storage>:1" \
                    "{\"method\":\"C\",\"target_disk\":\"$(json_escape "${OPT_DISK:-auto}")\",\"extra_disks_visible\":${extra}}" \
                    '{"summary":"Attach a second disk to the VM","command":"qm set <VMID> --scsi1 <storage>:1"}'
                die_prerequisite "Method C requires a second disk (found 0 additional block devices)"
            fi
            ;;
        *)
            die "internal: unknown method after detect: $method"
            ;;
    esac
}

# ── Distro-specific bootloader install (SDS-7 §3 Phase 8) ─────────────────

# Emit `--no-nvram` when running on a BIOS host (efivarfs absent), empty
# otherwise. grub*-install invokes efibootmgr internally to register the
# Boot#### entry; on BIOS that fails with "EFI variables are not supported
# on this system" and aborts the install. --no-nvram skips the registration
# step; phase 9 (`to_uefi_phase_9_uefi_entry`) handles entry creation post-
# UEFI-flip via populate_fallback_path, so nothing is lost.
# Populates GRUB_INSTALL_EXTRA_ARGS with --no-nvram when invoked under
# BIOS (/sys/firmware/efi/efivars absent), empty array otherwise. The
# array pattern is what callers want — string interpolation of a
# function whose output may be "" is what shellcheck SC2046 rightly
# flags, since an unquoted empty $(…) produces zero args while a
# quoted one produces a single empty-string arg. Both are wrong for
# pass-through to grub-install. Use the array at every call site.
GRUB_INSTALL_EXTRA_ARGS=()
set_grub_install_extra_args() {
    GRUB_INSTALL_EXTRA_ARGS=()
    [[ -d /sys/firmware/efi/efivars ]] || GRUB_INSTALL_EXTRA_ARGS=(--no-nvram)
}

install_grub_by_distro() {
    local esp_mount="$1"
    local distro
    distro=$(detect_distro)

    # Populate GRUB_INSTALL_EXTRA_ARGS once for whichever per-distro
    # callee runs below — each callee uses the array directly.
    set_grub_install_extra_args

    case "$distro" in
        ubuntu|debian|linuxmint|pop|elementary|kali)
            install_grub_apt "$esp_mount"
            ;;
        fedora|rhel|centos|rocky|almalinux|ol)
            install_grub_dnf "$esp_mount"
            ;;
        arch|endeavouros|manjaro|cachyos|artix)
            install_grub_pacman "$esp_mount"
            ;;
        opensuse*|sles|suse)
            install_grub_zypper "$esp_mount"
            ;;
        alpine)
            warn "Alpine Linux detected — GRUB install not automated in v1.0; install manually"
            return 1
            ;;
        *)
            warn "unknown distro: $distro — attempting generic grub-install"
            install_grub_generic "$esp_mount"
            ;;
    esac
}

install_grub_apt() {
    local esp_mount="$1"
    target_run apt-get install -y grub-efi-amd64 shim-signed \
        || die "apt install grub-efi-amd64 failed"
    target_run grub-install --target=x86_64-efi \
        --efi-directory="$esp_mount" \
        --bootloader-id=ubuntu \
        "${GRUB_INSTALL_EXTRA_ARGS[@]}" \
        || die "grub-install failed"
    # update-grub presence test must check inside chroot under Method B
    if [[ -n "$LAMBOOT_TARGET_ROOT" ]]; then
        [[ -x "$LAMBOOT_TARGET_ROOT/usr/sbin/update-grub" ]] && target_run update-grub
    else
        command -v update-grub >/dev/null 2>&1 && target_run update-grub
    fi
    record_action "bootloader.grub_efi.install" "apt" "ok" "false" '{"target":"x86_64-efi"}' "null"
}

install_grub_dnf() {
    local esp_mount="$1"
    target_run dnf install -y grub2-efi-x64 grub2-efi-x64-modules shim-x64 \
        || die "dnf install grub2-efi-x64 failed"
    target_run grub2-install --target=x86_64-efi \
        --efi-directory="$esp_mount" \
        --bootloader-id=fedora \
        "${GRUB_INSTALL_EXTRA_ARGS[@]}" \
        || die "grub2-install failed"

    local distro
    distro=$(detect_distro)
    target_run grub2-mkconfig -o "${esp_mount}/EFI/${distro}/grub.cfg"
    record_action "bootloader.grub_efi.install" "dnf" "ok" "false" '{"target":"x86_64-efi"}' "null"
}

install_grub_pacman() {
    local esp_mount="$1"
    # --needed: skip if already installed and current per local db. Without it,
    # pacman re-downloads "up to date" packages, which fails when mirrors no
    # longer carry the exact installed version (mirror has 19-1, local has 18-3).
    target_run pacman -S --needed --noconfirm grub efibootmgr \
        || die "pacman install grub failed"
    target_run grub-install --target=x86_64-efi \
        --efi-directory="$esp_mount" \
        --bootloader-id=arch \
        "${GRUB_INSTALL_EXTRA_ARGS[@]}" \
        || die "grub-install failed"
    target_run grub-mkconfig -o /boot/grub/grub.cfg
    record_action "bootloader.grub_efi.install" "pacman" "ok" "false" '{"target":"x86_64-efi"}' "null"
}

install_grub_zypper() {
    local esp_mount="$1"
    target_run zypper install -y grub2-x86_64-efi shim \
        || die "zypper install grub2-x86_64-efi failed"
    target_run grub2-install --target=x86_64-efi \
        --efi-directory="$esp_mount" \
        --bootloader-id=opensuse \
        "${GRUB_INSTALL_EXTRA_ARGS[@]}" \
        || die "grub2-install failed"
    if [[ -n "$LAMBOOT_TARGET_ROOT" ]]; then
        [[ -x "$LAMBOOT_TARGET_ROOT/usr/sbin/update-bootloader" ]] && target_run update-bootloader
    else
        command -v update-bootloader >/dev/null 2>&1 && target_run update-bootloader
    fi
    record_action "bootloader.grub_efi.install" "zypper" "ok" "false" '{"target":"x86_64-efi"}' "null"
}

install_grub_generic() {
    local esp_mount="$1"
    require_tool grub-install "install GRUB via your distro's package manager"
    lamboot_run grub-install --target=x86_64-efi \
        --efi-directory="$esp_mount" \
        "${GRUB_INSTALL_EXTRA_ARGS[@]}" \
        || die "generic grub-install failed"
    record_action "bootloader.grub_efi.install" "generic" "ok" "false" '{"target":"x86_64-efi"}' "null"
}

# ── to-uefi 10-phase pipeline (SDS-7 §3) ─────────────────────────────────

to_uefi_phase_1_preflight() {
    info "Phase 1 — Preflight"

    guard_boot_mode_is_bios
    guard_required_tools

    # Disk detection differs by method: Method B (live chroot) REQUIRES
    # --disk because findmnt / points at the live media, not the target;
    # Methods A/C auto-detect from root mount. Resolve before the method-
    # specific pre-check so we can diagnose precisely.
    local method
    method=$(detect_proxmox_method)
    if [[ "$method" != "B" ]] && [[ -z "$OPT_DISK" || "$OPT_DISK" == "/dev/null" ]]; then
        local disk
        disk=$(detect_target_disk) || die "cannot auto-detect target disk; use --disk"
        OPT_DISK="$disk"
    fi
    verbose "target disk: $OPT_DISK; method: $method"

    guard_method_prerequisites

    [[ -b "$OPT_DISK" ]] || die "not a block device: $OPT_DISK"

    guard_root_not_on_lvm_or_crypt
    guard_no_hybrid_mbr "$OPT_DISK"
    guard_no_windows "$OPT_DISK"
    guard_fstab_uuid_form

    # When an ESP already exists on the target disk (e.g. a previous run got as
    # far as Phase 5 before failing in Phase 8), Phase 5 will reuse it — so the
    # free-space check that determines "do we need to shrink to make room?"
    # would be wrong (ESP already takes the slack). Skip free-space + shrink
    # detection in that case.
    local existing_esp_chk
    existing_esp_chk=$(sgdisk -p "$OPT_DISK" 2>/dev/null | awk '$6 == "EF00" {print $1}' | head -1 || true)
    if [[ -n "$existing_esp_chk" ]]; then
        verbose "existing ESP on $OPT_DISK at partition $existing_esp_chk — skipping free-space check"
        emit_finding "migrate.preflight.existing_esp" "preflight" "info" "pass" \
            "Existing ESP detected — Phase 5 will reuse it" \
            "Partition $existing_esp_chk on $OPT_DISK is already an ESP. No shrink/create needed." \
            "{\"disk\":\"$(json_escape "$OPT_DISK")\",\"esp_part\":\"$existing_esp_chk\"}" '{}'
    else
        guard_disk_free_space "$OPT_DISK" "$OPT_ESP_SIZE_MB"
    fi
    guard_existing_esp_collision "$OPT_DISK" >/dev/null

    # Optional capcheck-driven readiness audit. Off by default;
    # opt-in via --capcheck-gate (or env LAMBOOT_MIGRATE_CAPCHECK=1).
    # Only critical-severity quirks abort; warnings are surfaced via findings.
    if [[ "${LAMBOOT_MIGRATE_CAPCHECK:-0}" == "1" ]] || [[ ${OPT_CAPCHECK_GATE:-0} -eq 1 ]]; then
        _capcheck_readiness_gate
    fi

    emit_finding "migrate.phase1.complete" "preflight" "info" "pass" \
        "Preflight checks passed" \
        "All safety gates cleared for $OPT_DISK." \
        "{\"disk\":\"$(json_escape "$OPT_DISK")\",\"esp_size_mb\":${OPT_ESP_SIZE_MB}}" \
        '{}'
    success "Phase 1 passed"
}

_capcheck_readiness_gate() {
    if ! command -v lamboot-capcheck >/dev/null 2>&1; then
        emit_finding "migrate.capcheck.unavailable" "preflight" "info" "pass" \
            "lamboot-capcheck not installed; skipping readiness audit" \
            "Install lamboot-capcheck for a full firmware capability audit before migration." \
            '{}' '{}'
        return 0
    fi
    if ! command -v jq >/dev/null 2>&1; then
        emit_finding "migrate.capcheck.no_jq" "preflight" "info" "pass" \
            "jq not installed; capcheck readiness audit skipped" \
            "Install jq to enable capcheck-driven preflight gating." \
            '{}' '{}'
        return 0
    fi

    info "Capability audit (lamboot-capcheck)"
    local audit
    audit=$(lamboot-capcheck --json audit 2>/dev/null || true)
    if [[ -z "$audit" ]]; then
        emit_finding "migrate.capcheck.no_output" "preflight" "warning" "warn" \
            "lamboot-capcheck produced no output" \
            "Could not run capcheck (permissions? offline mode?). Proceeding without capability audit." \
            '{}' '{}'
        return 0
    fi

    local critical_quirks
    critical_quirks=$(printf '%s' "$audit" | jq -r '.quirks_matched[] | select(.severity == "critical") | .id')
    if [[ -n "$critical_quirks" ]]; then
        local id_list
        id_list=$(printf '%s' "$critical_quirks" | tr '\n' ',' | sed 's/,$//')
        emit_finding "migrate.capcheck.critical_quirks" "preflight" "critical" "fail" \
            "Capability audit found critical firmware quirks: $id_list" \
            "lamboot-capcheck matched one or more quirks marked 'critical' against this hardware. Migration is unsafe until these are addressed. Run \`lamboot-capcheck quirks --list\` for details." \
            "{\"quirk_ids\":\"$(json_escape "$id_list")\"}" \
            '{"summary":"Resolve quirks before retrying","command":"lamboot-capcheck quirks --list","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
        die_prerequisite "capcheck preflight: critical quirks block migration ($id_list)"
    fi

    # Non-critical warnings → surfaced as info-level findings, do not abort.
    local warn_count
    warn_count=$(printf '%s' "$audit" | jq '.summary.checks_warn + .summary.checks_fail')
    if [[ "${warn_count:-0}" -gt 0 ]]; then
        local sample
        sample=$(printf '%s' "$audit" | jq -r '[.domains[] | .checks[] | select(.status == "fail" or .status == "warn") | .name] | join(", ")')
        emit_finding "migrate.capcheck.warnings" "preflight" "warning" "warn" \
            "Capability audit surfaced $warn_count non-critical issue(s)" \
            "These will not block migration but should be reviewed: $sample. Run \`lamboot-doctor\` after migration." \
            "{\"sample\":\"$(json_escape "$sample")\"}" '{}'
    else
        emit_finding "migrate.capcheck.clean" "preflight" "info" "pass" \
            "Capability audit clean" "lamboot-capcheck reports no critical findings." \
            '{}' '{}'
    fi
}

to_uefi_phase_2_confirm() {
    info "Phase 2 — Interactive confirmation"

    cat <<EOF >&2

Planned actions:
  Target disk:        $OPT_DISK
  ESP size:           ${OPT_ESP_SIZE_MB} MB
  Bootloader:         $OPT_BOOTLOADER
  Backup directory:   ${OPT_BACKUP_DIR:-/var/backups/lamboot-migrate-<auto>}
  Method:             $(detect_proxmox_method)

Point of no return is Phase 4 (MBR→GPT). Everything before that is reversible
without backup. Phase 5+ require backup for rollback.

EOF

    if ! confirm "CONVERT TO UEFI" "yes"; then
        record_action "migrate.user_aborted" "$OPT_DISK" "abort" "false" '{}' "null"
        emit_json "$EXIT_ABORT"
        exit "$EXIT_ABORT"
    fi
}

to_uefi_phase_3_backup() {
    info "Phase 3 — Backup"

    local backup_dir
    backup_dir="${OPT_BACKUP_DIR:-$(backup_dir_new migrate)}"
    OPT_BACKUP_DIR="$backup_dir"

    lamboot_run dd if="$OPT_DISK" "of=${backup_dir}/mbr-raw.bin" bs=1M count=1 status=none \
        || die "MBR backup failed"

    lamboot_run sgdisk "--backup=${backup_dir}/partition-table.gpt" "$OPT_DISK" \
        || die "partition table backup failed"

    backup_file_to "$backup_dir" /etc/fstab "fstab.pre-rewrite"
    backup_file_to "$backup_dir" /etc/default/grub "default-grub"
    backup_file_to "$backup_dir" /boot/grub/grub.cfg "grub.cfg"

    # Capture efivarfs state (may be empty on BIOS). The backup directory only
    # exists in non-dry-run mode (backup_dir_new prints the planned path but
    # doesn't mkdir it under --dry-run), so guard the file write accordingly.
    if [[ $LAMBOOT_DRY_RUN -eq 1 ]]; then
        printf 'DRY-RUN: would capture efibootmgr -v to %s/efi-vars.txt\n' "$backup_dir" >&2
    elif command -v efibootmgr >/dev/null 2>&1; then
        efibootmgr -v > "${backup_dir}/efi-vars.txt" 2>/dev/null || true
    fi

    record_action "migrate.backup_created" "$backup_dir" "ok" "true" \
        "{\"mbr_raw\":\"${backup_dir}/mbr-raw.bin\",\"disk\":\"$(json_escape "$OPT_DISK")\"}" \
        "$backup_dir"

    success "Phase 3 — backup saved: $backup_dir"
}

to_uefi_phase_3b_pre_mbr_to_gpt_shrink() {
    # Runs only when Phase 1 marked shrink needed. The shrink MUST happen
    # before Phase 4 (mbrtogpt), not after, because sgdisk --mbrtogpt silently
    # aborts (prints "Aborting write" but exits 0!) when the last MBR partition
    # extends into what would be the secondary GPT header at the end of the
    # disk. lamboot-migrate v1.0 had the shrink in Phase 5; this re-orders.
    [[ "${LAMBOOT_NEEDS_SHRINK:-0}" -eq 1 ]] || return 0

    info "Phase 3b — Pre-conversion shrink (avoid sgdisk --mbrtogpt overlap abort)"

    local shrink_dev="$LAMBOOT_SHRINK_LAST_PART_DEV"
    local shrink_num="$LAMBOOT_SHRINK_LAST_PART_NUM"
    local new_size_mb="$LAMBOOT_SHRINK_NEW_PART_MB"

    local mountpoint
    mountpoint=$(findmnt -n -o TARGET "$shrink_dev" 2>/dev/null | head -1 || true)
    if [[ -n "$mountpoint" ]]; then
        emit_finding "migrate.phase3b.cannot_shrink_mounted" "phase3b" "critical" "fail" \
            "Cannot shrink mounted filesystem $shrink_dev (at $mountpoint)" \
            "ext4 online resize supports growing only, never shrinking. Boot from a live ISO and re-run with --method=B." \
            "{\"device\":\"$(json_escape "$shrink_dev")\",\"mountpoint\":\"$(json_escape "$mountpoint")\"}" \
            '{"summary":"Boot live media + retry","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
        die "cannot shrink mounted $shrink_dev; reboot into live ISO and re-run with --method=B"
    fi

    # Step 1: shrink the ext4 filesystem inside the partition
    info "Phase 3b — resize2fs $shrink_dev to ${new_size_mb}M"
    lamboot_run e2fsck -fy "$shrink_dev" || die "e2fsck failed on $shrink_dev before shrink"
    lamboot_run resize2fs "$shrink_dev" "${new_size_mb}M" || die "resize2fs failed shrinking $shrink_dev"
    record_action "filesystem.resize" "$shrink_dev" "ok" "true" \
        "{\"new_size_mb\":${new_size_mb}}" "$OPT_BACKUP_DIR"

    # Step 2: shrink the MBR partition entry. sgdisk only writes GPT; this disk
    # is still MBR at Phase 3b, so use sfdisk in single-partition (-N) mode.
    local new_sectors
    new_sectors=$((new_size_mb * 1024 * 1024 / 512))
    if [[ $LAMBOOT_DRY_RUN -eq 1 ]]; then
        printf 'DRY-RUN: would exec: echo "size=%s" | sfdisk -N%s --no-reread --no-tell-kernel %s\n' \
            "$new_sectors" "$shrink_num" "$OPT_DISK" >&2
    else
        printf 'size=%s\n' "$new_sectors" \
            | sfdisk -N"$shrink_num" --no-reread --no-tell-kernel "$OPT_DISK" \
            || die "sfdisk MBR partition shrink failed for $OPT_DISK partition $shrink_num"
    fi
    lamboot_run partprobe "$OPT_DISK" 2>/dev/null || true
    record_action "partition.shrink_mbr" "$OPT_DISK" "ok" "true" \
        "{\"partition\":${shrink_num},\"new_sectors\":${new_sectors},\"new_size_mb\":${new_size_mb}}" \
        "$OPT_BACKUP_DIR"

    LAMBOOT_SHRINK_DONE=1
    success "Phase 3b — partition + ext4 shrunk to ${new_size_mb} MB (Phase 4 has end-of-disk slack now)"
}

to_uefi_phase_4_mbr_to_gpt() {
    info "Phase 4 — MBR→GPT conversion (point of no return for partition table)"

    local pttype
    pttype=$(blkid -o value -s PTTYPE "$OPT_DISK" 2>/dev/null || true)

    if [[ "$pttype" == "gpt" ]]; then
        verbose "disk is already GPT — skipping conversion"
        record_action "partition.mbrtogpt" "$OPT_DISK" "skipped" "false" '{"reason":"already_gpt"}' "null"
        return 0
    fi

    # sgdisk has a gotcha: it can print "Aborting write of new partition table"
    # when the last MBR partition overlaps the secondary GPT header — and exit
    # with status 0. So `|| die` is not enough; we must also parse stdout.
    if [[ $LAMBOOT_DRY_RUN -eq 1 ]]; then
        printf 'DRY-RUN: would exec: sgdisk --mbrtogpt %s\n' "$OPT_DISK" >&2
    else
        local sg_out sg_rc
        sg_out=$(sgdisk --mbrtogpt "$OPT_DISK" 2>&1); sg_rc=$?
        printf '%s\n' "$sg_out" >&2
        if [[ "$sg_out" == *"Aborting write"* ]]; then
            emit_finding "migrate.phase4.silent_abort" "phase4" "critical" "fail" \
                "sgdisk --mbrtogpt aborted write" \
                "sgdisk printed 'Aborting write' (overlap with secondary GPT header). Phase 3b should have pre-shrunk the last partition." \
                "{\"disk\":\"$(json_escape "$OPT_DISK")\"}" \
                '{"summary":"This is a bug — Phase 3b should run first","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
            die "sgdisk --mbrtogpt aborted write (overlap with secondary GPT header)"
        fi
        if [[ $sg_rc -ne 0 ]]; then
            die "sgdisk --mbrtogpt failed (exit $sg_rc)"
        fi
    fi

    record_action "partition.mbrtogpt" "$OPT_DISK" "ok" "true" '{}' "$OPT_BACKUP_DIR"
    success "Phase 4 — partition table converted to GPT"
}

to_uefi_phase_5_create_esp() {
    info "Phase 5 — Create ESP"

    # The shrink (when needed) was performed pre-conversion in Phase 3b. Phase
    # 5 now just places the ESP in the freed end-of-disk space. If Phase 1
    # marked shrink needed but Phase 3b somehow didn't run, that's a bug —
    # fail loudly so the disk doesn't get a too-small ESP carved out of a
    # still-full partition.
    if [[ "${LAMBOOT_NEEDS_SHRINK:-0}" -eq 1 ]] && [[ "${LAMBOOT_SHRINK_DONE:-0}" -ne 1 ]]; then
        die "internal: shrink was required but Phase 3b did not run (LAMBOOT_SHRINK_DONE=0)"
    fi

    local existing_esp
    existing_esp=$(sgdisk -p "$OPT_DISK" 2>/dev/null | awk '$6 == "EF00" {print $1}' | head -1 || true)

    local esp_partnum
    if [[ -n "$existing_esp" ]]; then
        esp_partnum="$existing_esp"
        verbose "reusing existing ESP partition $esp_partnum"
    else
        lamboot_run sgdisk --new="0:0:+${OPT_ESP_SIZE_MB}M" \
            --typecode="0:ef00" \
            --change-name="0:EFI System" \
            "$OPT_DISK" \
            || die "sgdisk --new for ESP failed"

        if [[ $LAMBOOT_DRY_RUN -eq 1 ]]; then
            # sgdisk didn't actually run; synthesize a plausible partnum so the
            # rest of the phase can print its planned actions without aborting.
            esp_partnum=$(sgdisk -p "$OPT_DISK" 2>/dev/null \
                | awk '$1 ~ /^[0-9]+$/ {print $1}' \
                | sort -n | tail -1 \
                | awk '{print $1+1}')
            esp_partnum="${esp_partnum:-99}"
            printf 'DRY-RUN: would assign ESP partition number %s on %s\n' "$esp_partnum" "$OPT_DISK" >&2
        else
            esp_partnum=$(sgdisk -p "$OPT_DISK" 2>/dev/null | awk '$6 == "EF00" {print $1}' | head -1 || true)
            [[ -n "$esp_partnum" ]] || die "ESP partition created but not detectable"
        fi

        record_action "partition.create_esp" "$OPT_DISK" "ok" "true" \
            "{\"partition\":${esp_partnum},\"size_mb\":${OPT_ESP_SIZE_MB}}" "$OPT_BACKUP_DIR"
    fi

    local esp_dev
    esp_dev=$(partition_device_for "$OPT_DISK" "$esp_partnum")

    lamboot_run partprobe "$OPT_DISK" 2>/dev/null || true

    if [[ -z "$existing_esp" ]]; then
        lamboot_run mkfs.vfat -F 32 -n ESP "$esp_dev" \
            || die "mkfs.vfat failed for $esp_dev"
        record_action "filesystem.format" "$esp_dev" "ok" "false" '{"fstype":"vfat","label":"ESP"}' "null"
    fi

    lamboot_run mkdir -p /boot/efi
    if ! mountpoint -q /boot/efi 2>/dev/null; then
        lamboot_run mount "$esp_dev" /boot/efi \
            || die "failed to mount $esp_dev at /boot/efi"
        record_action "filesystem.mount" "$esp_dev" "ok" "false" '{"mountpoint":"/boot/efi"}' "null"
    fi

    success "Phase 5 — ESP at $esp_dev mounted on /boot/efi"
    # Return via global var, not stdout. This function calls external
    # commands (sgdisk, mkfs.vfat, partprobe) that write to stdout, and
    # any of their output would otherwise bleed into the caller's $(...)
    # capture and corrupt esp_dev with command chatter like
    # "Creating new GPT entries in memory." or "mkfs.fat 4.2 (2021-01-31)".
    LAMBOOT_PHASE5_ESP_DEV="$esp_dev"
    # Persist the partition number too: Phase 9 needs it for efibootmgr --part,
    # and re-deriving it there via `sgdisk -p` returns empty in dry-run (no GPT
    # was actually written) and is redundant work in a real run.
    LAMBOOT_PHASE5_ESP_PARTNUM="$esp_partnum"
}

to_uefi_phase_5b_mount_target() {
    # Only Method B (live-ISO conversion) needs to mount the target — for
    # Method A we're already running on the system being converted and
    # /boot, /etc, /boot/efi are the target itself.
    local method
    method=$(detect_proxmox_method)
    [[ "$method" == "B" ]] || return 0

    info "Phase 5b — Mounting target root + ESP (Method B)"

    # Re-read partition table after Phase 5's resize/recreate
    lamboot_run partprobe "$OPT_DISK" 2>/dev/null || true

    # Target root is the partition we shrunk in Phase 5 (whose data is intact).
    local target_root_part="${LAMBOOT_SHRINK_LAST_PART_DEV:-}"
    if [[ -z "$target_root_part" ]]; then
        # Fall back to the first non-ESP partition
        target_root_part=$(sgdisk -p "$OPT_DISK" 2>/dev/null \
            | awk '$1 ~ /^[0-9]+$/ && $6 != "EF00" {print $1}' \
            | head -1)
        [[ -n "$target_root_part" ]] || die "could not find target root partition on $OPT_DISK"
        target_root_part=$(partition_device_for "$OPT_DISK" "$target_root_part")
    fi

    LAMBOOT_TARGET_ROOT="/mnt/lamboot-target"
    lamboot_run mkdir -p "$LAMBOOT_TARGET_ROOT"
    lamboot_run mount "$target_root_part" "$LAMBOOT_TARGET_ROOT" \
        || die "failed to mount target root $target_root_part at $LAMBOOT_TARGET_ROOT"
    record_action "method_b.mount.root" "$target_root_part" "ok" "false" \
        "{\"mountpoint\":\"$(json_escape "$LAMBOOT_TARGET_ROOT")\"}" "null"

    # Mount any separate /boot (or /usr, /var) the target declares in fstab,
    # BEFORE the ESP, so grub-install/grub-mkconfig in Phase 8 see the real
    # kernel images and embed a correct prefix (SDS-7 separate-/boot fix).
    mount_target_separate_filesystems

    # Mount the ESP we just created under target's /boot/efi so the bootloader
    # installer in Phase 8 writes EFI/<distro>/grubx64.efi to the correct place.
    local esp_dev="${LAMBOOT_PHASE5_ESP_DEV:-}"
    [[ -n "$esp_dev" ]] || die "Phase 5 did not record ESP device (LAMBOOT_PHASE5_ESP_DEV unset)"
    lamboot_run mkdir -p "$LAMBOOT_TARGET_ROOT/boot/efi"
    lamboot_run mount "$esp_dev" "$LAMBOOT_TARGET_ROOT/boot/efi" \
        || die "failed to mount ESP $esp_dev at $LAMBOOT_TARGET_ROOT/boot/efi"
    record_action "method_b.mount.esp" "$esp_dev" "ok" "false" \
        "{\"mountpoint\":\"$(json_escape "$LAMBOOT_TARGET_ROOT/boot/efi")\"}" "null"

    success "Phase 5b — target accessible at $LAMBOOT_TARGET_ROOT (root + ESP)"
}

to_uefi_phase_6_fstab() {
    info "Phase 6 — fstab rewrite"

    local esp_dev="$1"
    local esp_uuid
    esp_uuid=$(blkid -s UUID -o value "$esp_dev" 2>/dev/null || true)
    if [[ -z "$esp_uuid" ]]; then
        if [[ $LAMBOOT_DRY_RUN -eq 1 ]]; then
            # Dry-run: ESP was never actually created/formatted, so blkid has
            # nothing to read. Use an all-zero UUID so the rest of the phase
            # can print its plan without aborting; real runs always read live.
            esp_uuid="00000000-0000-0000-0000-000000000000"
            printf 'DRY-RUN: synthesized all-zero ESP UUID (real run reads from blkid)\n' >&2
        else
            die "could not read UUID for $esp_dev"
        fi
    fi

    # Target's fstab: live ISO's /etc/fstab under Method A (in-place),
    # /mnt/lamboot-target/etc/fstab under Method B.
    local fstab_path
    fstab_path=$(target_path /etc/fstab)

    if [[ $LAMBOOT_DRY_RUN -eq 0 ]]; then
        [[ -f "$fstab_path" ]] || die "target fstab not found at $fstab_path"

        local new_fstab
        new_fstab=$(mktemp)

        # Rewrite any /dev/sd* or /dev/nvme* or /dev/hd* references to UUID= form
        while IFS= read -r line; do
            if [[ "$line" =~ ^[[:space:]]*/dev/(sd[a-z]|nvme|hd[a-z]) ]]; then
                local dev
                dev=$(printf '%s' "$line" | awk '{print $1}')
                local uuid
                uuid=$(blkid -s UUID -o value "$dev" 2>/dev/null || true)
                if [[ -n "$uuid" ]]; then
                    printf '%s\n' "$line" | sed "s|^${dev}|UUID=${uuid}|"
                    verbose "rewrote fstab: $dev → UUID=$uuid"
                else
                    printf '%s\n' "$line"
                fi
            else
                printf '%s\n' "$line"
            fi
        done < "$fstab_path" > "$new_fstab"

        # Append ESP entry if not already present
        if ! grep -q "$esp_uuid" "$new_fstab"; then
            printf 'UUID=%s /boot/efi vfat umask=0077,shortname=winnt 0 1\n' "$esp_uuid" >> "$new_fstab"
        fi

        mv "$new_fstab" "$fstab_path"
        chmod 0644 "$fstab_path"
    else
        printf 'DRY-RUN: would rewrite %s with UUID=%s mount at /boot/efi\n' "$fstab_path" "$esp_uuid" >&2
    fi

    record_action "fstab.rewrite" "$fstab_path" "ok" "true" \
        "{\"esp_uuid\":\"$(json_escape "$esp_uuid")\"}" "$OPT_BACKUP_DIR"

    success "Phase 6 — fstab rewritten with UUID= entries"
}

to_uefi_phase_7_chroot_prep() {
    info "Phase 7 — Chroot prep"

    # Method A runs on the live target itself: /proc, /sys, /dev, /run are
    # already mounted and the running kernel sees them — nothing to do.
    if [[ -z "$LAMBOOT_TARGET_ROOT" ]]; then
        verbose "Method A: skipping bind-mounts (already on running target)"
        success "Phase 7 — chroot prep complete (Method A no-op)"
        return 0
    fi

    # Method B: bind-mount kernel virtual filesystems + DNS into the target so
    # Phase 8's package-manager + grub-install invocations work properly inside
    # chroot. Tracked in LAMBOOT_TARGET_BINDS for cleanup on exit.
    local bind src dst
    for bind in /dev /proc /sys /run; do
        dst="${LAMBOOT_TARGET_ROOT}${bind}"
        if mountpoint -q "$dst" 2>/dev/null; then
            verbose "already bound: $dst"
            continue
        fi
        lamboot_run mkdir -p "$dst"
        lamboot_run mount --bind "$bind" "$dst" || die "bind-mount $bind → $dst failed"
        LAMBOOT_TARGET_BINDS+=("$dst")
    done

    # DNS for package downloads inside chroot
    if [[ -f /etc/resolv.conf ]]; then
        if [[ ! -e "${LAMBOOT_TARGET_ROOT}/etc/resolv.conf" || ! -s "${LAMBOOT_TARGET_ROOT}/etc/resolv.conf" ]]; then
            lamboot_run cp -L /etc/resolv.conf "${LAMBOOT_TARGET_ROOT}/etc/resolv.conf" \
                || verbose "could not copy resolv.conf into target (may break package install)"
        fi
    fi

    # efivarfs — usually absent during Method B (live ISO is BIOS-booted).
    # When absent, Phase 9 falls back to deferred boot-entry creation, which is
    # the right behavior. When present (rare: UEFI live ISO), bind it in.
    if [[ -d /sys/firmware/efi/efivars ]]; then
        dst="${LAMBOOT_TARGET_ROOT}/sys/firmware/efi/efivars"
        lamboot_run mkdir -p "$dst"
        lamboot_run mount --bind /sys/firmware/efi/efivars "$dst" 2>/dev/null \
            && LAMBOOT_TARGET_BINDS+=("$dst") \
            || verbose "efivarfs bind-mount failed (Phase 9 will defer boot-entry creation)"
    fi

    success "Phase 7 — chroot prep complete (4 virtual FS bind-mounted to $LAMBOOT_TARGET_ROOT)"
}

to_uefi_phase_8_install_bootloader() {
    info "Phase 8 — Install bootloader ($OPT_BOOTLOADER)"

    case "$OPT_BOOTLOADER" in
        grub-efi)
            install_grub_by_distro /boot/efi
            ;;
        lamboot)
            install_grub_by_distro /boot/efi
            # lamboot-install must run inside the target chroot under Method B
            # so it edits the target's ESP + writes the target's manifest.
            local lamboot_install_path
            if [[ -n "$LAMBOOT_TARGET_ROOT" ]]; then
                lamboot_install_path="$LAMBOOT_TARGET_ROOT/usr/bin/lamboot-install"
                [[ -x "$lamboot_install_path" ]] || lamboot_install_path="$LAMBOOT_TARGET_ROOT/usr/local/bin/lamboot-install"
            else
                lamboot_install_path=$(command -v lamboot-install || true)
            fi
            if [[ -n "$lamboot_install_path" && -x "$lamboot_install_path" ]]; then
                # Do NOT pass --with-drivers here. That legacy flag
                # rewrites to OPT_WITH_DRIVERS_LEGACY="all" (the v0.8.3
                # force-install-regardless mode), which fights native
                # coverage (SDS-2 ext4, Path A btrfs) and produces
                # bogus "missing driver" failures for filesystems that
                # don't need a driver. Let lamboot-install's SDS-6 auto
                # mode decide per-fstype.
                target_run lamboot-install --set-default \
                    || die "lamboot-install failed"
                record_action "bootloader.lamboot.install" "/boot/efi/EFI/LamBoot" "ok" "false" '{}' "null"
            elif [[ $LAMBOOT_DRY_RUN -eq 1 && -n "$LAMBOOT_TARGET_ROOT" ]]; then
                # The Phase 5b target mount was a dry-run no-op, so the target's
                # /usr/bin is not actually populated here — detection can't run.
                # A real run mounts the target first and finds lamboot-install.
                printf 'DRY-RUN: would run lamboot-install --set-default in target (detection skipped: target not mounted in dry-run)\n' >&2
            else
                warn "lamboot-install not found in target; GRUB installed as fallback"
                warn "install LamBoot later: https://github.com/lamco-admin/lamboot-tools"
            fi
            ;;
        systemd-boot)
            if [[ -n "$LAMBOOT_TARGET_ROOT" ]]; then
                [[ -x "$LAMBOOT_TARGET_ROOT/usr/bin/bootctl" ]] \
                    || die "bootctl not found in target ($LAMBOOT_TARGET_ROOT/usr/bin/bootctl)"
            else
                require_tool bootctl "install systemd-boot via your distro's package manager"
            fi
            target_run bootctl install || die "bootctl install failed"
            record_action "bootloader.systemd-boot.install" "/boot/efi" "ok" "false" '{}' "null"
            ;;
        *)
            die "unknown bootloader: $OPT_BOOTLOADER (use grub-efi, lamboot, or systemd-boot)"
            ;;
    esac

    success "Phase 8 — bootloader installed"
}

to_uefi_phase_9_uefi_entry() {
    info "Phase 9 — UEFI boot entry"

    # On a BIOS-booted host, efibootmgr can't write NVRAM (no efivarfs).
    # Method B (live chroot) or post-reboot-into-UEFI is the actual creation moment.
    if [[ ! -d /sys/firmware/efi/efivars ]]; then
        warn "efivarfs not available on BIOS boot — UEFI boot entry will be created on first UEFI boot"
        record_action "uefi.boot_entry.deferred" "EFI/BOOT/BOOTX64.EFI" "skipped" "false" \
            '{"reason":"no_efivarfs"}' "null"

        # Populate the fallback path so firmware-removable-boot picks it up
        populate_fallback_path
        return 0
    fi

    # Prefer the partnum Phase 5 recorded; fall back to deriving it from the live
    # GPT only if that global is somehow unset (e.g. Phase 5 was skipped because
    # an ESP already existed and the run resumed mid-pipeline).
    local esp_partnum="${LAMBOOT_PHASE5_ESP_PARTNUM:-}"
    if [[ -z "$esp_partnum" ]]; then
        esp_partnum=$(sgdisk -p "$OPT_DISK" 2>/dev/null | awk '$6 == "EF00" {print $1}' | head -1 || true)
    fi
    [[ -n "$esp_partnum" ]] || die "cannot determine ESP partition number for efibootmgr"

    local distro
    distro=$(detect_distro)

    local loader_path="\\EFI\\${distro}\\grubx64.efi"
    [[ "$OPT_BOOTLOADER" == "lamboot" ]] && loader_path="\\EFI\\LamBoot\\lambootx64.efi"

    lamboot_run efibootmgr --create --disk "$OPT_DISK" --part "$esp_partnum" \
        --loader "$loader_path" \
        --label "LamBoot-migrated $(date +%Y-%m-%d)" \
        || die "efibootmgr --create failed"

    record_action "uefi.boot_entry.create" "$loader_path" "ok" "true" \
        "{\"disk\":\"$(json_escape "$OPT_DISK")\",\"part\":${esp_partnum}}" "$OPT_BACKUP_DIR"

    populate_fallback_path

    success "Phase 9 — UEFI boot entry created"
}

populate_fallback_path() {
    # Under Method B, /boot/efi here means the target's ESP (mounted at
    # $LAMBOOT_TARGET_ROOT/boot/efi). target_path() resolves correctly for both
    # methods; target_run() handles the chroot wrapping for cp/mkdir.
    target_run mkdir -p /boot/efi/EFI/BOOT

    # Source-loader search must inspect the ACTUAL filesystem (not the live
    # ISO's), so we look on disk through target_path() rather than via glob
    # inside chroot.
    local source_loader=""
    case "$OPT_BOOTLOADER" in
        grub-efi)
            local esp_root
            esp_root=$(target_path /boot/efi)
            for candidate in "$esp_root"/EFI/*/grubx64.efi "$esp_root"/EFI/*/shimx64.efi; do
                [[ -f "$candidate" ]] && {
                    # Strip the LAMBOOT_TARGET_ROOT prefix to get the path-as-seen-from-chroot
                    source_loader="${candidate#${LAMBOOT_TARGET_ROOT}}"
                    break
                }
            done
            ;;
        lamboot)
            source_loader="/boot/efi/EFI/LamBoot/lambootx64.efi"
            ;;
        systemd-boot)
            source_loader="/boot/efi/EFI/systemd/systemd-bootx64.efi"
            ;;
    esac

    if [[ -n "$source_loader" ]] && [[ -f "$(target_path "$source_loader")" ]]; then
        target_run cp "$source_loader" /boot/efi/EFI/BOOT/BOOTX64.EFI
        record_action "uefi.fallback_path.populate" "/boot/efi/EFI/BOOT/BOOTX64.EFI" "ok" "false" \
            "{\"source\":\"$(json_escape "$source_loader")\"}" "null"
    elif [[ $LAMBOOT_DRY_RUN -eq 1 ]]; then
        # Phase 8's bootloader install was a dry-run no-op, so its loader was
        # never written to the ESP — there's nothing to copy yet. A real run
        # installs the loader first, then this finds and mirrors it.
        printf 'DRY-RUN: would copy %s → /boot/efi/EFI/BOOT/BOOTX64.EFI (source not present under --dry-run)\n' "$source_loader" >&2
    else
        warn "could not find a source loader for fallback path population"
    fi
}

# run_method_b_offline_checks — artifact validation that does NOT require a UEFI
# boot, run on the still-mounted target after a Method B conversion. Catches the
# separate-/boot / kernel-less-grub.cfg failure class BEFORE the migration is
# declared a success (SDS-7: previously Method B deferred all checks and marked
# success on an unbootable disk). Returns the count of failed checks (0 = good).
run_method_b_offline_checks() {
    [[ $LAMBOOT_DRY_RUN -eq 1 ]] && { verbose "offline-verify: skipped under --dry-run"; return 0; }
    local troot="$LAMBOOT_TARGET_ROOT" fails=0

    # 1. A kernel must be visible in the target's /boot — proves a separate
    #    /boot partition (if any) is actually mounted into the chroot.
    if [[ $(find "$troot/boot" -maxdepth 1 -name 'vmlinuz-*' 2>/dev/null | wc -l) -eq 0 ]]; then
        warn "offline-verify: no vmlinuz-* under $troot/boot (separate /boot not mounted?)"
        fails=$((fails+1))
    fi

    # 2. For grub-efi, grub.cfg must exist AND carry a real kernel menuentry —
    #    a kernel-less config is exactly what an empty chroot /boot produces.
    if [[ "$OPT_BOOTLOADER" == "grub-efi" ]]; then
        local cfg="$troot/boot/grub/grub.cfg"
        if [[ ! -s "$cfg" ]] || ! grep -qE '^[[:space:]]*menuentry[[:space:]]' "$cfg" 2>/dev/null; then
            warn "offline-verify: $cfg missing or has no menuentry (grub-mkconfig found no kernel)"
            fails=$((fails+1))
        elif ! grep -qE '^[[:space:]]*linux[[:space:]]' "$cfg" 2>/dev/null; then
            warn "offline-verify: $cfg has menuentries but no 'linux' kernel line"
            fails=$((fails+1))
        fi
    fi

    # 3. The ESP must carry the firmware fallback loader so OVMF can boot it
    #    even before a UEFI NVRAM entry exists.
    if [[ ! -e "$troot/boot/efi/EFI/BOOT/BOOTX64.EFI" ]]; then
        warn "offline-verify: ESP fallback \\EFI\\BOOT\\BOOTX64.EFI is missing"
        fails=$((fails+1))
    fi

    return "$fails"
}

to_uefi_phase_10_verify() {
    info "Phase 10 — Verify"

    if [[ $OPT_SKIP_VERIFY -eq 1 ]]; then
        verbose "skipping verification (--skip-verify)"
        return 0
    fi

    # Method B runs from a BIOS-booted live ISO — verify checks like "boot
    # mode is UEFI" + "efibootmgr lists target entry" can't pass yet; they
    # become meaningful only after the user switches firmware and boots the
    # converted system. Defer verify with a clear next-step instruction.
    if [[ -n "$LAMBOOT_TARGET_ROOT" ]]; then
        # The boot-mode / efibootmgr checks need a UEFI boot, but the artifact
        # checks below run offline on the still-mounted target and catch the
        # class of failure that previously shipped a "successful" yet unbootable
        # disk. Refuse to mark the backup successful unless they pass.
        local b_fail=0
        run_method_b_offline_checks || b_fail=$?
        if [[ $b_fail -ne 0 ]]; then
            warn "Phase 10 — $b_fail offline artifact check(s) failed; NOT marking migration successful"
            warn "the converted disk would not boot as-is; run 'lamboot-migrate rollback' to revert"
            emit_finding "migrate.phase10.method_b_offline_fail" "phase10" "error" "fail" \
                "Offline checks failed (Method B)" \
                "$b_fail post-conversion artifact check(s) failed on the mounted target; the disk is not bootable." \
                "{\"failures\":${b_fail}}" \
                '{"summary":"Inspect warnings above, then rollback","command":"sudo lamboot-migrate rollback"}'
            emit_json "$EXIT_PARTIAL"
            exit "$EXIT_PARTIAL"
        fi
        warn "Phase 10 — offline artifact checks passed; UEFI-boot checks deferred"
        warn "After switching firmware to UEFI and booting, run: sudo lamboot-migrate verify"
        emit_finding "migrate.phase10.method_b_offline_ok" "phase10" "info" "pass" \
            "Offline checks passed (Method B)" \
            "Kernel, grub.cfg menuentry, and ESP fallback loader validated on the mounted target; boot-mode checks deferred to first UEFI boot." \
            "{\"reason\":\"live_iso_is_bios\"}" \
            '{"summary":"Run verify after UEFI boot","command":"sudo lamboot-migrate verify"}'
        backup_success "$OPT_BACKUP_DIR"
        return 0
    fi

    local fail_count=0
    run_verify_checks || fail_count=$?

    if [[ $fail_count -eq 0 ]]; then
        backup_success "$OPT_BACKUP_DIR"
        success "Phase 10 — all 12 verification checks passed"
    else
        warn "Phase 10 — $fail_count verification check(s) failed; system in EXIT_PARTIAL state"
        warn "run 'lamboot-migrate verify' to inspect, or 'lamboot-migrate rollback' to revert"
        emit_json "$EXIT_PARTIAL"
        exit "$EXIT_PARTIAL"
    fi
}

do_to_uefi() {
    require_root

    # Ensure Method B mount + bind state is cleaned up on any exit path.
    # Idempotent + no-op for Method A.
    trap cleanup_target_mounts EXIT

    to_uefi_phase_1_preflight
    to_uefi_phase_2_confirm
    to_uefi_phase_3_backup
    to_uefi_phase_3b_pre_mbr_to_gpt_shrink
    to_uefi_phase_4_mbr_to_gpt
    local esp_dev
    to_uefi_phase_5_create_esp
    esp_dev="$LAMBOOT_PHASE5_ESP_DEV"
    to_uefi_phase_5b_mount_target
    to_uefi_phase_6_fstab "$esp_dev"
    to_uefi_phase_7_chroot_prep
    to_uefi_phase_8_install_bootloader
    to_uefi_phase_9_uefi_entry
    to_uefi_phase_10_verify

    # Method-specific "what now?" guidance
    local method
    method=$(detect_proxmox_method)
    if [[ "$method" == "B" ]]; then
        cat <<EOF >&2

Migration complete (Method B — live-ISO conversion).

Next steps:
  1. shutdown the live ISO: sudo poweroff
  2. At Proxmox host: detach the ISO, switch to OVMF, add an EFI vars disk:
       qm shutdown <VMID>
       qm set <VMID> --delete ide2
       qm set <VMID> --bios ovmf --efidisk0 <storage>:1,efitype=4m
       qm set <VMID> --boot order=scsi0
  3. Seed a UEFI boot entry into the fresh EFI vars. A new efidisk has an empty
     BootOrder and OVMF does not reliably auto-launch the \\EFI\\BOOT\\ fallback,
     so without this the VM comes up with "no bootable device":
       VARS=\$(pvesm path <storage>:vm-<VMID>-disk-N)   # the efidisk0 volume
       virt-fw-vars --inplace "\$VARS" --append-boot-filepath '/EFI/BOOT/BOOTX64.EFI'
       qm start <VMID>
  4. After UEFI boot, run: sudo lamboot-migrate verify

Backup retained: $OPT_BACKUP_DIR
Rollback available: sudo lamboot-migrate rollback

EOF
    else
        cat <<EOF >&2

Migration complete.

Next steps:
  1. Reboot.
  2. Enter firmware setup (usually F2/F12/DEL at POST).
  3. Switch from Legacy/CSM to UEFI mode.
  4. Boot. Your system will come up via UEFI.

Proxmox VMs:
  qm shutdown <VMID>
  qm set <VMID> --bios ovmf --efidisk0 <storage>:1,efitype=4m --machine q35
  qm start <VMID>

Backup retained: $OPT_BACKUP_DIR
Rollback available: sudo lamboot-migrate rollback

EOF
    fi

    emit_json "$EXIT_OK"
}

# ── to-lamboot (SDS-7 §2.2) ──────────────────────────────────────────────

do_to_lamboot() {
    require_root

    if [[ ! -d /sys/firmware/efi ]]; then
        emit_finding "migrate.to_lamboot.not_uefi" "firmware" "critical" "fail" \
            "System is not booted in UEFI mode" \
            "Run 'lamboot-migrate to-uefi' first to convert BIOS/MBR to UEFI/GPT." \
            "{}" \
            '{"summary":"Run to-uefi first","command":"sudo lamboot-migrate to-uefi","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
        emit_json "$EXIT_NOT_APPLICABLE"
        exit "$EXIT_NOT_APPLICABLE"
    fi

    local backup_dir
    backup_dir=$(backup_dir_new to-lamboot)

    # Snapshot current bootloader state
    if command -v efibootmgr >/dev/null 2>&1; then
        efibootmgr -v > "${backup_dir}/efi-vars.txt" 2>/dev/null || true
    fi

    if ! command -v lamboot-install >/dev/null 2>&1; then
        die_prerequisite "lamboot-install not found; install the LamBoot bootloader package first"
    fi

    # NOTE: --with-drivers was historically passed here, but as of
    # lamboot-install v0.9.1+ (commit 50c7da0) it's obsolete: lamboot-install's
    # SDS-6 native-coverage detection always wins in "auto" mode, and the
    # legacy "all" mode that --with-drivers sets would force-install
    # _x64.efi drivers that may not exist in release tarballs (because
    # native ext4-view + native lambutter btrfs deprecated them). Dropping
    # the flag makes to-lamboot behave correctly on systems with natively-
    # covered /boot filesystems (ext4 on Proxmox/Debian/Ubuntu, btrfs on
    # openSUSE/Garuda/CachyOS).
    local install_args=()
    if [[ $OPT_UNSIGNED -eq 1 ]]; then
        verbose "to-lamboot: --unsigned set, omitting --signed from lamboot-install args"
    else
        install_args+=("--signed")
    fi
    [[ $OPT_PRESERVE_GRUB -eq 1 ]] && install_args+=("--set-default")

    lamboot_run lamboot-install "${install_args[@]}" \
        || die "lamboot-install failed"

    record_action "bootloader.lamboot.install" "/boot/efi/EFI/LamBoot" "ok" "false" \
        "{\"preserve_grub\":$([[ $OPT_PRESERVE_GRUB -eq 1 ]] && printf 'true' || printf 'false')}" \
        "$backup_dir"

    if [[ $OPT_REMOVE_GRUB -eq 1 ]]; then
        _remove_grub "$backup_dir"
    fi

    backup_success "$backup_dir"
    success "LamBoot installed. Reboot to test."
    success "If LamBoot fails, use firmware boot menu to select previous bootloader."
    success "Rollback: sudo lamboot-migrate rollback --backup-dir $backup_dir"

    emit_json "$EXIT_OK"
}

# ── --remove-grub: uninstall prior bootloader after LamBoot is verified ──
#
# Flow:
#   1. Run the full 12-check verify pass. Refuse to remove if any fail.
#   2. Confirm with typed-yes (unless --force / --yes / --auto).
#   3. Snapshot the NVRAM + GRUB package list into $backup_dir for rollback.
#   4. Distro-aware package uninstall (apt/dnf/pacman/zypper/generic).
#   5. Remove GRUB files from the ESP (every known installation path).
#   6. Remove GRUB Boot#### entries from NVRAM via efibootmgr -b <hex> -B.
#   7. Record a migrate.to_lamboot.grub_removed action for the manifest.
#
# Refuses to remove if /boot/efi/EFI/LamBoot isn't present. Rollback is
# possible via the saved NVRAM snapshot + the distro's package cache.

_distro_grub_packages() {
    local distro="$1"
    case "$distro" in
        debian|ubuntu|pop|linuxmint)
            printf 'grub-efi-amd64 grub-efi-amd64-bin grub-efi-amd64-signed grub2-common grub-common shim-signed'
            ;;
        fedora|rhel|centos|rocky|almalinux)
            printf 'grub2-efi-x64 grub2-efi-x64-modules grub2-tools grub2-tools-efi grub2-tools-extra grub2-tools-minimal grub2-common shim-x64'
            ;;
        arch|endeavouros|manjaro|cachyos)
            printf 'grub efibootmgr-grub-tools'
            ;;
        opensuse*|sles|suse)
            printf 'grub2 grub2-i386-pc grub2-x86_64-efi grub2-snapper-plugin'
            ;;
        *)
            printf ''  # generic — no package removal
            ;;
    esac
}

_distro_uninstall_cmd() {
    local distro="$1" pkgs="$2"
    [[ -z "$pkgs" ]] && { printf ''; return; }
    case "$distro" in
        debian|ubuntu|pop|linuxmint)
            printf 'apt-get purge -y %s' "$pkgs"
            ;;
        fedora|rhel|centos|rocky|almalinux)
            printf 'dnf remove -y %s' "$pkgs"
            ;;
        arch|endeavouros|manjaro|cachyos)
            printf 'pacman -Rns --noconfirm %s' "$pkgs"
            ;;
        opensuse*|sles|suse)
            printf 'zypper remove -y %s' "$pkgs"
            ;;
        *)
            printf ''
            ;;
    esac
}

_remove_grub_nvram_entries() {
    # Parse efibootmgr for entries containing GRUB/grub/shim; delete each.
    local efi_output removed_nums removed=0 bootnum label
    efi_output=$(efibootmgr -v 2>/dev/null) || return 0

    while IFS= read -r line; do
        # Format: Boot0001* ubuntu	HD(...)/File(\EFI\ubuntu\shimx64.efi)...
        [[ "$line" =~ ^Boot([0-9A-Fa-f]{4})\*?\ (.*) ]] || continue
        bootnum="${BASH_REMATCH[1]}"
        label="${BASH_REMATCH[2]}"
        # Match common GRUB/shim entry names (case-insensitive, narrow to avoid
        # false positives like "Windows Boot Manager")
        if [[ "$line" =~ (grub|GRUB|shim|Shim|SHIM|ubuntu|debian|fedora|opensuse|centos|rocky|almalinux|arch|manjaro|endeavour) ]]; then
            # Exclude LamBoot explicitly in case a distro label collides
            [[ "$label" =~ LamBoot ]] && continue
            lamboot_run efibootmgr --quiet --bootnum "$bootnum" --delete-bootnum \
                && removed=$((removed + 1)) \
                && removed_nums="${removed_nums:+$removed_nums }$bootnum" \
                || warn "failed to remove Boot$bootnum ($label)"
        fi
    done <<< "$efi_output"

    printf '%d' "$removed"
}

_remove_grub_esp_files() {
    local esp="$1" removed=0
    # Known GRUB/shim paths across distros.
    local paths=(
        "$esp/EFI/GRUB"
        "$esp/EFI/grub"
        "$esp/EFI/debian"
        "$esp/EFI/ubuntu"
        "$esp/EFI/fedora"
        "$esp/EFI/centos"
        "$esp/EFI/redhat"
        "$esp/EFI/opensuse"
        "$esp/EFI/arch"
        "$esp/EFI/Manjaro"
        "$esp/EFI/endeavouros"
        "$esp/EFI/almalinux"
        "$esp/EFI/rocky"
        "$esp/grub"
        "$esp/grub2"
    )
    for p in "${paths[@]}"; do
        if [[ -e "$p" ]]; then
            lamboot_run rm -rf "$p" && removed=$((removed + 1)) \
                || warn "failed to remove: $p"
        fi
    done
    printf '%d' "$removed"
}

_remove_grub() {
    local backup_dir="$1"

    info "Running post-install verify before GRUB removal..."
    local verify_fail=0
    run_verify_checks || verify_fail=$?

    if [[ $verify_fail -gt 0 ]]; then
        die "verify failed with $verify_fail check(s); refusing to remove GRUB. Boot LamBoot successfully first, then re-run with --remove-grub."
    fi

    # Defense-in-depth: confirm LamBoot files are actually on the ESP.
    local esp
    esp=$(detect_esp) || die "cannot locate ESP for GRUB removal"
    if [[ ! -d "$esp/EFI/LamBoot" ]]; then
        die "refusing to remove GRUB: $esp/EFI/LamBoot not found — LamBoot may not be installed"
    fi

    if ! confirm "REMOVE GRUB PACKAGES + ESP FILES + NVRAM ENTRIES (irreversible without rollback)" "remove-grub"; then
        warn "--remove-grub aborted; LamBoot installed, GRUB retained"
        return 0
    fi

    # Snapshot NVRAM for rollback context
    efibootmgr -v > "${backup_dir}/efi-vars.pre-grub-removal.txt" 2>/dev/null || true

    local distro pkgs uninst
    distro=$(detect_distro)
    pkgs=$(_distro_grub_packages "$distro")
    uninst=$(_distro_uninstall_cmd "$distro" "$pkgs")

    local pkg_removed=0
    if [[ -n "$uninst" ]]; then
        info "Uninstalling distro GRUB packages: $pkgs"
        # Record pre-removal package list so rollback can reinstall
        case "$distro" in
            debian|ubuntu|pop|linuxmint)
                dpkg -l 2>/dev/null | awk '/^ii/ && $2 ~ /^(grub|shim)/ {print $2}' \
                    > "${backup_dir}/grub-packages.txt" 2>/dev/null || true
                ;;
            fedora|rhel|centos|rocky|almalinux)
                rpm -qa --qf '%{NAME}\n' 2>/dev/null | grep -E '^(grub2|shim)' \
                    > "${backup_dir}/grub-packages.txt" 2>/dev/null || true
                ;;
            arch|endeavouros|manjaro|cachyos)
                pacman -Qq grub 2>/dev/null > "${backup_dir}/grub-packages.txt" || true
                ;;
            opensuse*|sles|suse)
                rpm -qa --qf '%{NAME}\n' 2>/dev/null | grep -E '^grub2' \
                    > "${backup_dir}/grub-packages.txt" 2>/dev/null || true
                ;;
        esac

        if lamboot_run sh -c "$uninst"; then
            pkg_removed=1
        else
            warn "package uninstall reported failure; continuing with ESP + NVRAM cleanup (packages may be partially removed)"
        fi
    else
        info "No package removal recipe for distro '$distro'; skipping package step (ESP + NVRAM cleanup will still run)"
    fi

    info "Removing GRUB files from ESP at $esp"
    local esp_removed
    esp_removed=$(_remove_grub_esp_files "$esp")
    info "Removed $esp_removed ESP directory(ies)"

    info "Removing GRUB/shim Boot#### entries from NVRAM"
    local nvram_removed
    nvram_removed=$(_remove_grub_nvram_entries)
    info "Removed $nvram_removed NVRAM entry(ies)"

    record_action "migrate.to_lamboot.grub_removed" "$esp" "ok" "true" \
        "{\"distro\":\"$distro\",\"pkg_removed\":$pkg_removed,\"esp_dirs_removed\":$esp_removed,\"nvram_entries_removed\":$nvram_removed,\"packages_list\":\"${backup_dir}/grub-packages.txt\"}" \
        "$backup_dir"

    success "GRUB removed. To restore, use: sudo lamboot-migrate rollback --backup-dir $backup_dir"
}

# ── verify (SDS-7 §2.3, 12 checks) ───────────────────────────────────────

verify_check_1_boot_mode_uefi() {
    if [[ -d /sys/firmware/efi ]]; then
        emit_finding "migrate.verify.boot_mode" "verify" "info" "pass" \
            "Check 1: Boot mode is UEFI" "/sys/firmware/efi exists." "{}" '{}'
        return 0
    fi
    emit_finding "migrate.verify.boot_mode" "verify" "critical" "fail" \
        "Check 1: Boot mode is NOT UEFI" "/sys/firmware/efi not present." "{}" \
        '{"summary":"Switch firmware from Legacy/CSM to UEFI","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
    return 1
}

verify_check_2_disk_is_gpt() {
    local disk
    disk=$(detect_target_disk) || disk="/dev/sda"
    local pttype
    pttype=$(blkid -o value -s PTTYPE "$disk" 2>/dev/null || true)
    if [[ "$pttype" == "gpt" ]]; then
        emit_finding "migrate.verify.gpt" "verify" "info" "pass" \
            "Check 2: Disk is GPT" "Partition table on $disk is GPT." \
            "{\"disk\":\"$(json_escape "$disk")\"}" '{}'
        return 0
    fi
    emit_finding "migrate.verify.gpt" "verify" "error" "fail" \
        "Check 2: Disk is NOT GPT" "Partition table on $disk is '$pttype' (expected gpt)." \
        "{\"disk\":\"$(json_escape "$disk")\",\"pttype\":\"$pttype\"}" \
        '{"summary":"Run lamboot-migrate to-uefi","command":"sudo lamboot-migrate to-uefi","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
    return 1
}

verify_check_3_esp_exists_ef00() {
    # Method C (add-ESP-disk) places the ESP on a *separate* disk from
    # the root disk, so the historical check that only scanned the root
    # disk would false-fail for every Method C install. Scan all block
    # devices for any EF00 partition; report the first one found.
    local found_disk="" found_part=""
    local disk
    for disk in $(lsblk -ndo NAME,TYPE 2>/dev/null | awk '$2 == "disk" {print "/dev/" $1}'); do
        local part
        part=$(sgdisk -p "$disk" 2>/dev/null | awk '$6 == "EF00" {print $1}' | head -1 || true)
        if [[ -n "$part" ]]; then
            found_disk="$disk"
            found_part="$part"
            break
        fi
    done

    if [[ -n "$found_disk" ]]; then
        emit_finding "migrate.verify.esp_partition" "verify" "info" "pass" \
            "Check 3: ESP partition present (type EF00)" \
            "ESP is partition $found_part on $found_disk." \
            "{\"disk\":\"$(json_escape "$found_disk")\",\"partition\":$found_part}" '{}'
        return 0
    fi
    emit_finding "migrate.verify.esp_partition" "verify" "critical" "fail" \
        "Check 3: No ESP partition found" \
        "No partition on any disk has type EF00." \
        "{}" \
        '{"summary":"Create ESP via lamboot-migrate to-uefi","command":"sudo lamboot-migrate to-uefi","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
    return 1
}

verify_check_4_esp_mounted() {
    for mp in /boot/efi /efi; do
        if mountpoint -q "$mp" 2>/dev/null; then
            local fstype
            fstype=$(findmnt -n -o FSTYPE "$mp" 2>/dev/null || true)
            if [[ "$fstype" == "vfat" ]]; then
                emit_finding "migrate.verify.esp_mounted" "verify" "info" "pass" \
                    "Check 4: ESP mounted" "$mp mounted as vfat." \
                    "{\"mountpoint\":\"$mp\"}" '{}'
                return 0
            fi
        fi
    done
    emit_finding "migrate.verify.esp_mounted" "verify" "error" "fail" \
        "Check 4: ESP not mounted" \
        "Neither /boot/efi nor /efi is a vfat mountpoint." "{}" \
        '{"summary":"Mount the ESP","command":"sudo mount /boot/efi","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
    return 1
}

verify_check_5_efibootmgr_entries() {
    if ! command -v efibootmgr >/dev/null 2>&1; then
        emit_finding "migrate.verify.efibootmgr" "verify" "warning" "skip" \
            "Check 5: efibootmgr not available" "Install efibootmgr." "{}" \
            '{"summary":"Install efibootmgr","command":"sudo apt install efibootmgr || sudo dnf install efibootmgr","doc_url":""}'
        return 1
    fi
    local entries
    entries=$(efibootmgr 2>/dev/null | grep -cE '^Boot[0-9A-Fa-f]{4}' || true)
    entries="${entries:-0}"
    if [[ "$entries" -gt 0 ]]; then
        emit_finding "migrate.verify.efibootmgr" "verify" "info" "pass" \
            "Check 5: UEFI boot entries present" \
            "$entries entry/entries in NVRAM." \
            "{\"count\":${entries}}" '{}'
        return 0
    fi
    emit_finding "migrate.verify.efibootmgr" "verify" "error" "fail" \
        "Check 5: No UEFI boot entries" "efibootmgr shows 0 entries." "{}" \
        '{"summary":"Create boot entry via bootloader reinstall","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
    return 1
}

verify_check_6_fallback_path() {
    if [[ -f /boot/efi/EFI/BOOT/BOOTX64.EFI ]]; then
        emit_finding "migrate.verify.fallback_path" "verify" "info" "pass" \
            "Check 6: Fallback path present" \
            "/boot/efi/EFI/BOOT/BOOTX64.EFI exists." "{}" '{}'
        return 0
    fi
    emit_finding "migrate.verify.fallback_path" "verify" "warning" "fail" \
        "Check 6: Fallback path missing" \
        "/boot/efi/EFI/BOOT/BOOTX64.EFI not present (removable/portable boot will not work)." "{}" \
        '{"summary":"Run to-uefi which populates the fallback path","command":"sudo lamboot-migrate to-uefi","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
    return 1
}

verify_check_7_bootloader_pe32() {
    local found=""
    for candidate in /boot/efi/EFI/*/grubx64.efi /boot/efi/EFI/LamBoot/lambootx64.efi /boot/efi/EFI/systemd/systemd-bootx64.efi; do
        [[ -f "$candidate" ]] && { found="$candidate"; break; }
    done

    if [[ -z "$found" ]]; then
        emit_finding "migrate.verify.pe32_bootloader" "verify" "error" "fail" \
            "Check 7: No bootloader binary found" \
            "No grubx64.efi, lambootx64.efi, or systemd-bootx64.efi on ESP." "{}" \
            '{"summary":"Reinstall the bootloader","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
        return 1
    fi

    local info
    info=$(file "$found" 2>/dev/null || true)
    if printf '%s' "$info" | grep -q 'PE32+'; then
        emit_finding "migrate.verify.pe32_bootloader" "verify" "info" "pass" \
            "Check 7: Bootloader is PE32+ (EFI application)" \
            "$found is a valid UEFI binary." \
            "{\"path\":\"$(json_escape "$found")\"}" '{}'
        return 0
    fi

    emit_finding "migrate.verify.pe32_bootloader" "verify" "critical" "fail" \
        "Check 7: Bootloader is NOT PE32+" \
        "$found is not a UEFI binary (may be BIOS GRUB instead)." \
        "{\"path\":\"$(json_escape "$found")\",\"type\":\"$(json_escape "$info")\"}" \
        '{"summary":"Reinstall with --target=x86_64-efi","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
    return 1
}

verify_check_8_fstab_uses_uuids() {
    local dev_entries
    dev_entries=$(grep -cE '^\s*/dev/sd[a-z]|^\s*/dev/nvme|^\s*/dev/hd[a-z]' /etc/fstab 2>/dev/null || true)
    dev_entries="${dev_entries:-0}"
    if [[ "$dev_entries" -eq 0 ]]; then
        emit_finding "migrate.verify.fstab_uuid" "verify" "info" "pass" \
            "Check 8: fstab uses UUID= form" \
            "No /dev/ references in /etc/fstab." "{}" '{}'
        return 0
    fi
    emit_finding "migrate.verify.fstab_uuid" "verify" "warning" "fail" \
        "Check 8: fstab still has /dev/ paths" \
        "${dev_entries} fstab entries use /dev/ paths." \
        "{\"count\":${dev_entries}}" \
        '{"summary":"Rewrite fstab to UUID form","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
    return 1
}

verify_check_9_boot_has_kernels() {
    local kernel_count
    kernel_count=$(find "$(target_path /boot)" -maxdepth 1 -name 'vmlinuz-*' 2>/dev/null | wc -l)
    if [[ "$kernel_count" -gt 0 ]]; then
        emit_finding "migrate.verify.kernels_present" "verify" "info" "pass" \
            "Check 9: Kernel(s) present in /boot" \
            "$kernel_count kernel image(s) found." \
            "{\"count\":${kernel_count}}" '{}'
        return 0
    fi
    emit_finding "migrate.verify.kernels_present" "verify" "error" "fail" \
        "Check 9: No kernels in /boot" \
        "/boot has no vmlinuz-* files." "{}" \
        '{"summary":"Reinstall kernel package","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
    return 1
}

verify_check_10_backup_manifest_valid() {
    local backup_path="${OPT_VERIFY_PATH:-}"
    if [[ -z "$backup_path" ]]; then
        backup_path=$(backup_latest migrate)
    fi
    if [[ -z "$backup_path" ]] || [[ ! -d "$backup_path" ]]; then
        emit_finding "migrate.verify.backup_manifest" "verify" "warning" "skip" \
            "Check 10: No backup directory to verify" \
            "No prior to-uefi backup found; check inapplicable." "{}" '{}'
        return 0
    fi
    if [[ -f "$backup_path/MANIFEST.json" ]]; then
        if command -v jq >/dev/null 2>&1; then
            if jq -e . "$backup_path/MANIFEST.json" >/dev/null 2>&1; then
                emit_finding "migrate.verify.backup_manifest" "verify" "info" "pass" \
                    "Check 10: Backup manifest valid JSON" \
                    "$backup_path/MANIFEST.json parses cleanly." "{}" '{}'
                return 0
            fi
        else
            emit_finding "migrate.verify.backup_manifest" "verify" "info" "pass" \
                "Check 10: Backup manifest present" \
                "$backup_path/MANIFEST.json exists (jq not installed — content not validated)." "{}" '{}'
            return 0
        fi
    fi
    emit_finding "migrate.verify.backup_manifest" "verify" "warning" "fail" \
        "Check 10: Backup manifest missing or invalid" \
        "$backup_path/MANIFEST.json not valid JSON or absent." \
        "{\"backup_dir\":\"$(json_escape "$backup_path")\"}" '{}'
    return 1
}

verify_check_11_rollback_dry_run() {
    local backup_path="${OPT_VERIFY_PATH:-}"
    if [[ -z "$backup_path" ]]; then
        backup_path=$(backup_latest migrate)
    fi
    if [[ -z "$backup_path" ]] || [[ ! -d "$backup_path" ]]; then
        emit_finding "migrate.verify.rollback_ready" "verify" "info" "skip" \
            "Check 11: No backup to dry-run rollback against" \
            "Skipped (no backup dir)." "{}" '{}'
        return 0
    fi
    local missing=()
    for f in mbr-raw.bin partition-table.gpt fstab.pre-rewrite; do
        [[ -f "$backup_path/$f" ]] || missing+=("$f")
    done
    if [[ ${#missing[@]} -eq 0 ]]; then
        emit_finding "migrate.verify.rollback_ready" "verify" "info" "pass" \
            "Check 11: Rollback backup files complete" \
            "All required rollback files present in $backup_path." "{}" '{}'
        return 0
    fi
    emit_finding "migrate.verify.rollback_ready" "verify" "warning" "fail" \
        "Check 11: Rollback backup incomplete" \
        "Missing: ${missing[*]}" \
        "{\"missing\":[\"$(printf '%s' "${missing[*]}" | sed 's/ /","/g')\"]}" '{}'
    return 1
}

verify_check_12_fallback_identity() {
    # The firmware-removable fallback (\EFI\BOOT\BOOTX64.EFI) decides what boots
    # when there is no NVRAM entry. It MUST be byte-identical to the intended
    # primary loader — not a stale or foreign binary (e.g. GRUB's shim). This is
    # the md5/sha check the migration case studies do by hand (SPEC §6.1).
    local fb=/boot/efi/EFI/BOOT/BOOTX64.EFI primary=""
    local cand
    for cand in /boot/efi/EFI/LamBoot/lambootx64.efi /boot/efi/EFI/*/grubx64.efi; do
        [[ -f "$cand" ]] && { primary="$cand"; break; }
    done
    if [[ ! -f "$fb" || -z "$primary" ]]; then
        emit_finding "migrate.verify.fallback_identity" "verify" "info" "skip" \
            "Check 12: Fallback identity not applicable" \
            "No fallback path or no primary loader to compare against." "{}" '{}'
        return 0
    fi
    local fb_sha pr_sha
    fb_sha=$(sha256sum "$fb" 2>/dev/null | awk '{print $1}')
    pr_sha=$(sha256sum "$primary" 2>/dev/null | awk '{print $1}')
    if [[ -n "$fb_sha" && "$fb_sha" == "$pr_sha" ]]; then
        emit_finding "migrate.verify.fallback_identity" "verify" "info" "pass" \
            "Check 12: Fallback is the intended loader" \
            "\\EFI\\BOOT\\BOOTX64.EFI is byte-identical to ${primary##*/}." \
            "{\"sha256\":\"$(json_escape "$fb_sha")\"}" '{}'
        return 0
    fi
    emit_finding "migrate.verify.fallback_identity" "verify" "warning" "fail" \
        "Check 12: Fallback is NOT the intended loader" \
        "\\EFI\\BOOT\\BOOTX64.EFI does not match $primary — the firmware fallback may boot a different or stale loader." \
        "{\"fallback_sha\":\"$(json_escape "$fb_sha")\",\"primary_sha\":\"$(json_escape "$pr_sha")\",\"primary\":\"$(json_escape "$primary")\"}" \
        '{"summary":"Re-run to-uefi to repopulate the fallback","command":"sudo lamboot-migrate to-uefi","doc_url":"https://github.com/lamco-admin/lamboot-tools"}'
    return 1
}

run_verify_checks() {
    local fail=0
    verify_check_1_boot_mode_uefi       || fail=$((fail + 1))
    verify_check_2_disk_is_gpt          || fail=$((fail + 1))
    verify_check_3_esp_exists_ef00      || fail=$((fail + 1))
    verify_check_4_esp_mounted          || fail=$((fail + 1))
    verify_check_5_efibootmgr_entries   || fail=$((fail + 1))
    verify_check_6_fallback_path        || fail=$((fail + 1))
    verify_check_7_bootloader_pe32      || fail=$((fail + 1))
    verify_check_8_fstab_uses_uuids     || fail=$((fail + 1))
    verify_check_9_boot_has_kernels     || fail=$((fail + 1))
    verify_check_10_backup_manifest_valid || fail=$((fail + 1))
    verify_check_11_rollback_dry_run    || fail=$((fail + 1))
    verify_check_12_fallback_identity   || fail=$((fail + 1))
    return $fail
}

do_verify() {
    info "Running post-conversion verification (12 checks)"
    local fail=0
    run_verify_checks || fail=$?

    if [[ $fail -eq 0 ]]; then
        success "All 12 verification checks passed"
        emit_json "$EXIT_OK"
        exit "$EXIT_OK"
    fi

    warn "$fail check(s) failed — see findings above"
    emit_json "$EXIT_PARTIAL"
    exit "$EXIT_PARTIAL"
}

# ── rollback (SDS-7 §7.2) ────────────────────────────────────────────────

do_rollback() {
    require_root

    local backup_dir="${OPT_BACKUP_DIR:-}"
    if [[ -z "$backup_dir" ]]; then
        backup_dir=$(backup_latest migrate)
    fi

    if [[ -z "$backup_dir" ]] || [[ ! -d "$backup_dir" ]]; then
        emit_finding "migrate.rollback.no_backup" "rollback" "critical" "fail" \
            "No backup directory found" \
            "No previous to-uefi run to roll back from." "{}" '{}'
        emit_json "$EXIT_NOT_APPLICABLE"
        exit "$EXIT_NOT_APPLICABLE"
    fi

    if [[ ! -f "$backup_dir/MANIFEST.json" ]]; then
        die "backup dir missing MANIFEST.json: $backup_dir"
    fi

    local disk
    disk=$(grep -oE '"[^"]*":\s*"/dev/[^"]*"' "$backup_dir/MANIFEST.json" | head -1 | grep -oE '/dev/[^"]*' || true)
    if [[ -z "$disk" ]]; then
        warn "could not extract disk from MANIFEST.json; using auto-detected"
        disk=$(detect_target_disk) || die "cannot determine target disk for rollback"
    fi

    cat <<EOF >&2

Rollback plan:
  Backup dir:    $backup_dir
  Target disk:   $disk
  Will restore:  MBR, partition table, fstab, default-grub (if present)
  Will remove:   UEFI boot entries created by to-uefi

After rollback, switch firmware back to Legacy/CSM to boot via MBR.

EOF

    if ! confirm "ROLLBACK" "yes"; then
        record_action "migrate.rollback_aborted" "$backup_dir" "abort" "false" '{}' "null"
        emit_json "$EXIT_ABORT"
        exit "$EXIT_ABORT"
    fi

    # Restore fstab
    if [[ -f "$backup_dir/fstab.pre-rewrite" ]]; then
        lamboot_run cp "$backup_dir/fstab.pre-rewrite" /etc/fstab
        record_action "fstab.restore" "/etc/fstab" "ok" "false" \
            "{\"from\":\"$(json_escape "$backup_dir/fstab.pre-rewrite")\"}" "null"
    fi

    # Restore /etc/default/grub
    if [[ -f "$backup_dir/default-grub" ]]; then
        lamboot_run cp "$backup_dir/default-grub" /etc/default/grub
        record_action "grub.default_restore" "/etc/default/grub" "ok" "false" '{}' "null"
    fi

    # Remove UEFI boot entries we created
    if [[ -d /sys/firmware/efi/efivars ]] && command -v efibootmgr >/dev/null 2>&1; then
        local entries
        entries=$(efibootmgr 2>/dev/null | grep -oE '^Boot[0-9A-Fa-f]{4}\*?\s+LamBoot-migrated' | grep -oE '[0-9A-Fa-f]{4}' || true)
        while IFS= read -r entry; do
            [[ -z "$entry" ]] && continue
            lamboot_run efibootmgr --bootnum "$entry" --delete-bootnum
            record_action "uefi.boot_entry.remove" "Boot$entry" "ok" "false" '{}' "null"
        done <<< "$entries"
    fi

    # Zap GPT and restore MBR
    lamboot_run sgdisk --zap-all "$disk" \
        || warn "sgdisk --zap-all failed (may be expected if disk already in post-zap state)"

    lamboot_run dd "if=$backup_dir/mbr-raw.bin" "of=$disk" bs=1M count=1 status=none \
        || die "MBR restore failed"

    record_action "partition.mbr_restore" "$disk" "ok" "false" \
        "{\"from\":\"$(json_escape "$backup_dir/mbr-raw.bin")\"}" "null"

    if [[ -f "$backup_dir/partition-table.gpt" ]]; then
        verbose "sfdisk-format backup available but skipping restore (MBR takes precedence)"
    fi

    # Append to ROLLBACK.log
    if [[ $LAMBOOT_DRY_RUN -eq 0 ]]; then
        cat >> "$backup_dir/ROLLBACK.log" <<EOF
$(date -u +%Y-%m-%dT%H:%M:%SZ) rollback executed on $(hostname)
  disk=$disk
  run_id=$LAMBOOT_RUN_ID
EOF
    fi

    success "Rollback complete"
    success "Switch firmware back to Legacy/CSM and reboot"
    emit_json "$EXIT_OK"
}

# ── status (kept from v0.1.0, formalized) ────────────────────────────────

do_status() {
    local boot_mode
    boot_mode=$(detect_boot_mode)
    info "Boot mode: $boot_mode"
    emit_finding "migrate.status.boot_mode" "status" "info" "pass" \
        "Boot mode: $boot_mode" "System is in $boot_mode mode." \
        "{\"mode\":\"$boot_mode\"}" '{}'

    local disk
    disk=$(detect_target_disk) || disk=""

    if [[ -n "$disk" ]]; then
        local pttype
        pttype=$(blkid -o value -s PTTYPE "$disk" 2>/dev/null || true)
        info "Target disk: $disk (${pttype:-no-partition-table})"
        emit_finding "migrate.status.partition_table" "status" "info" "pass" \
            "Partition table: $pttype" "Disk $disk uses $pttype." \
            "{\"disk\":\"$(json_escape "$disk")\",\"pttype\":\"$pttype\"}" '{}'
    fi

    local bootloaders
    bootloaders=$(list_bootloaders 2>/dev/null | paste -sd, - || true)
    info "Installed bootloaders: ${bootloaders:-none}"
    emit_finding "migrate.status.bootloaders" "status" "info" "pass" \
        "Installed bootloaders: ${bootloaders:-none}" \
        "" \
        "{\"bootloaders\":\"$(json_escape "${bootloaders:-none}")\"}" '{}'

    local distro distro_ver
    distro=$(detect_distro)
    distro_ver=$(detect_distro_version)
    info "Distribution: $distro $distro_ver"
    emit_finding "migrate.status.distro" "status" "info" "pass" \
        "Distribution: $distro $distro_ver" "" \
        "{\"id\":\"$distro\",\"version\":\"$distro_ver\"}" '{}'

    # Migration readiness summary
    if [[ "$boot_mode" == "bios" ]] && [[ -n "$disk" ]]; then
        local pttype
        pttype=$(blkid -o value -s PTTYPE "$disk" 2>/dev/null || true)
        if [[ "$pttype" == "dos" ]]; then
            warn "Ready for BIOS→UEFI migration — run: sudo lamboot-migrate to-uefi --disk $disk"
            emit_finding "migrate.status.readiness" "status" "warning" "warn" \
                "Ready for BIOS→UEFI migration" \
                "System is BIOS+MBR. Run 'sudo lamboot-migrate to-uefi --disk $disk' to convert." \
                "{\"action\":\"to-uefi\"}" \
                "{\"summary\":\"Run to-uefi conversion\",\"command\":\"sudo lamboot-migrate to-uefi --disk $disk\",\"doc_url\":\"https://github.com/lamco-admin/lamboot-tools\"}"
        fi
    fi

    if [[ $LAMBOOT_JSON -eq 1 ]]; then
        emit_json "$EXIT_OK"
    fi
}

# ── CLI ──────────────────────────────────────────────────────────────────

show_version() {
    printf 'lamboot-migrate %s (lamboot-tools %s)\n' \
        "$LAMBOOT_TOOL_VERSION" "$LAMBOOT_TOOLKIT_VERSION"
}

show_help() {
    print_after_help
}

parse_args() {
    [[ $# -eq 0 ]] && { die "no subcommand (try: lamboot-migrate help)"; }

    # The first positional that is a known subcommand name captures the
    # subcommand; subsequent positionals are arguments to it. This prevents
    # `help to-uefi` from overwriting OPT_SUBCOMMAND=help with to-uefi.
    local positional=()
    while [[ $# -gt 0 ]]; do
        if [[ -z "$OPT_SUBCOMMAND" ]]; then
            case "$1" in
                to-uefi|to-lamboot|verify|rollback|status|help)
                    OPT_SUBCOMMAND="$1"
                    shift
                    continue
                    ;;
            esac
        fi
        positional+=("$1")
        shift
    done

    if [[ "$OPT_SUBCOMMAND" == "help" ]]; then
        _register_subcommands
        if [[ ${#positional[@]} -eq 0 ]]; then
            dispatch_help
            exit 0
        fi
        dispatch_help "${positional[0]}"
        exit $?
    fi

    set -- "${positional[@]+${positional[@]}}"

    # Second pass: parse flags
    while [[ $# -gt 0 ]]; do
        parse_common_flag "$1"
        local rc=$?
        case $rc in
            1) shift; continue ;;
            2) _register_subcommands
               if [[ -n "$OPT_SUBCOMMAND" ]]; then
                   dispatch_help "$OPT_SUBCOMMAND"
               else
                   dispatch_help
               fi
               exit 0 ;;
            3) show_version; exit 0 ;;
            4) printf '{"$schema":"https://github.com/lamco-admin/lamboot-tools"}\n'; exit 0 ;;
            5) shift; OPT_DISK="$1"; shift; continue ;;
            0) ;;
        esac

        # Accept both --opt=value and --opt value forms. Split the equals form
        # into two args so the case below stays simple.
        if [[ "$1" == --*=* ]]; then
            set -- "${1%%=*}" "${1#*=}" "${@:2}"
        fi

        case "$1" in
            --disk)         OPT_DISK="${2:-}"; shift 2 ;;
            --esp-size)     OPT_ESP_SIZE_MB="${2:-550}"; shift 2 ;;
            --bootloader)   OPT_BOOTLOADER="${2:-grub-efi}"; shift 2 ;;
            --cmdline)      OPT_CMDLINE="${2:-}"; shift 2 ;;
            --backup-dir)   OPT_BACKUP_DIR="${2:-}"; shift 2 ;;
            --method)       OPT_METHOD="${2:-auto}"; shift 2 ;;
            --skip-verify)  OPT_SKIP_VERIFY=1; shift ;;
            --keep-legacy-mbr) OPT_KEEP_LEGACY_MBR=1; shift ;;
            --preserve-grub) OPT_PRESERVE_GRUB=1; OPT_REMOVE_GRUB=0; shift ;;
            --remove-grub)   OPT_REMOVE_GRUB=1; OPT_PRESERVE_GRUB=0; shift ;;
            --unsigned)     OPT_UNSIGNED=1; shift ;;
            --capcheck-gate) OPT_CAPCHECK_GATE=1; shift ;;
            --all)          OPT_VERIFY_ALL=1; shift ;;
            --path)         OPT_VERIFY_PATH="${2:-}"; shift 2 ;;
            *)              die "unknown option: $1" ;;
        esac
    done
}

main() {
    parse_args "$@"

    case "$OPT_SUBCOMMAND" in
        to-uefi)    do_to_uefi ;;
        to-lamboot) do_to_lamboot ;;
        verify)     do_verify ;;
        rollback)   do_rollback ;;
        status)     do_status ;;
        "")         die "no subcommand specified (try: lamboot-migrate help)" ;;
        *)          die "unknown subcommand: $OPT_SUBCOMMAND" ;;
    esac
}

# Run main only when this file is executed directly, not when sourced
# (which bats integration tests do to call guard_* / detect_* functions
# against loopback-mounted fixtures).
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi
