#!/bin/bash

# omarchy:summary=Build and publish the boot images systemd-boot starts, with a menu entry per snapshot
# omarchy:args=sync | import PKGBASE KVER VMLINUZ INITRAMFS | pin NUMBER | prefer PKGBASE | preferred | windows | cmdline | verify | status | restore-stage SNAPSHOT|backup | restore-commit | restore-cancel
# omarchy:hidden=true
# omarchy:requires-sudo=true

# On a machine that boots systemd-boot (see omarchy-boot-switch), every kernel
# build is a boot image: kernel, initramfs and the command line in effect when
# it was built, kept on the encrypted root in the boot store, a top-level btrfs
# subvolume mounted at /var/lib/omarchy/boot so a snapshot restore never rolls
# it back. Each boot image becomes one Unified Kernel Image in $BOOT, and the
# live system and every snapshot taken on that image are profiles inside it:
#
#   omarchy-<machine>-<pkgbase>-<hash>.efi
#     .linux .initrd .cmdline .osrel .uname             shared
#     .profile omarchy      the live system                    (when installed)
#     .profile snapshot-12  .cmdline rootflags=subvol=@/.snapshots/12/snapshot
#
# systemd-boot lists every profile as its own entry, and systemd-stub ignores
# any command line passed from outside the image when Secure Boot is on, so
# each snapshot's root selection has to be inside the image.
#
# A snapshot is pinned to the boot image current when it was taken, so rolling
# back from a broken kernel, initramfs or command line change boots the old
# ones. Snapshots taken before the machine switched to systemd-boot have no pin
# and are not offered; omarchy-boot-switch deletes them when it finishes.

set -euo pipefail

STORE=${OMARCHY_BOOT_STORE:-/var/lib/omarchy/boot}
# The ESP systemd-boot starts from, with loader.conf, and $BOOT, where the
# boot images go: an XBOOTLDR partition beside Windows' ESP, or the same ESP.
# Where omarchy-boot-partitions can't tell (it says why), only what touches
# neither partition runs.
if [[ -n ${OMARCHY_BOOT_ESP:-} ]]; then
  ESP=$OMARCHY_BOOT_ESP BOOT=${OMARCHY_BOOT_XBOOTLDR:-$OMARCHY_BOOT_ESP}
elif partitions=$(omarchy-boot-partitions); then
  IFS=$'\t' read -r ESP BOOT <<<"$partitions"
else
  case ${1:-} in
  cmdline | preferred) ESP="" BOOT="" ;;
  *) exit 1 ;;
  esac
fi
TOP=${OMARCHY_BOOT_TOP:-/run/omarchy-boot/top}
LOCK=${OMARCHY_BOOT_LOCK:-/run/omarchy-boot.lock}
# ukify picks the stub for the machine's architecture. The image itself reads
# /etc/kernel/uki.conf, where Snapdragon machines list their device trees
# (omarchy-update-qualcomm-device-trees); profiles read nothing, so the trees
# are carried once rather than copied into every profile.
UKI_CONFIG=${OMARCHY_BOOT_UKI_CONFIG:-/etc/kernel/uki.conf}
HWIDS=${OMARCHY_BOOT_HWIDS:-/usr/lib/systemd/boot/hwids}
MAX_SNAPSHOTS=${OMARCHY_BOOT_MAX_SNAPSHOTS:-6}
MACHINE_ID_FILE=${OMARCHY_BOOT_MACHINE_ID:-/etc/machine-id}
LOADER_GUID=4a67b082-0a4c-41cf-b6c7-440b29bb8c4f

# Bumped when the image layout changes, so published images get rebuilt.
FORMAT=4
CA_PEM=${OMARCHY_BOOT_CA_PEM:-${OMARCHY_PATH:-/usr/share/omarchy}/default/boot/omarchy-secure-boot-ca.pem}
CA_SHA256=${OMARCHY_BOOT_CA_SHA256:-b9b3aef73dd1b80336f2ecd768a96d7697decbc1e22e23c6f9311c069c997307}
CA_VERIFIED=0
SIGNED_LOADER=${OMARCHY_BOOT_SIGNED_LOADER:-/usr/lib/systemd/boot/efi/systemd-bootx64.efi.signed}
SECURE_BOOT_SWITCHES="lockdown=integrity iommu.passthrough=0 intel_iommu=on sysctl.kernel.kexec_load_disabled=1"
MODE_OVERRIDE=""

BUILD_WORK=""
BUILD_STAGED=""
WINDOWS_WORK=""
cleanup_work() {
  [[ -z ${BUILD_WORK:-} ]] || rm -rf "$BUILD_WORK"
  [[ -z ${BUILD_STAGED:-} ]] || rm -f "$BUILD_STAGED"
  [[ -z ${WINDOWS_WORK:-} ]] || rm -rf "$WINDOWS_WORK"
}
trap cleanup_work EXIT

die() {
  echo "omarchy-boot-sync: $*" >&2
  exit 1
}

log() {
  echo "omarchy-boot-sync: $*"
}

# --- state ------------------------------------------------------------------

# The store keeps small KEY=value files. They are parsed, never sourced.
kv_get() {
  local file=$1 key=$2
  [[ -f $file ]] || return 0
  sed -n "s/^$key=//p" "$file" | tail -1
}

kv_set() {
  local file=$1 key=$2 value=$3 tmp
  tmp=$(mktemp "$file.XXXXXX")
  if [[ -f $file ]]; then
    grep -v "^$key=" "$file" >"$tmp" || true
  fi
  printf '%s=%s\n' "$key" "$value" >>"$tmp"
  chmod 0644 "$tmp"
  sync "$tmp" 2>/dev/null || true
  mv -f "$tmp" "$file"
  sync "$(dirname "$file")" 2>/dev/null || true
}

state_get() { kv_get "$STORE/state" "$1"; }
state_set() { kv_set "$STORE/state" "$1" "$2"; }

effective_secure_boot() {
  if [[ -n $MODE_OVERRIDE ]]; then
    echo "$MODE_OVERRIDE"
  else
    state_get secure_boot
  fi
}

namespace() {
  local id
  id=$(<"$MACHINE_ID_FILE")
  echo "${id:0:8}"
}

# --- mounts ------------------------------------------------------------------

# Writing into an unmounted /var/lib/omarchy/boot would put boot images on the
# root that a restore replaces, so every writer checks the mount first.
check_store() {
  [[ ${OMARCHY_BOOT_TEST:-} == "1" ]] && return 0
  local fstype fsroot
  read -r fstype fsroot < <(findmnt -n -o FSTYPE,FSROOT --mountpoint "$STORE" 2>/dev/null) ||
    die "the boot store is not mounted at $STORE"
  # A factory reset builds the next root's store as @omarchy-boot-next, the
  # name it keeps until that root is activated.
  [[ $fstype == "btrfs" && ($fsroot == /@omarchy-boot || $fsroot == /@omarchy-boot-next) ]] ||
    die "$STORE is $fstype $fsroot, not the @omarchy-boot subvolume"
}

# Likewise the ESP: written while it isn't mounted, the images would land on
# the root, and verify would pass on them while the firmware boots stale ones.
check_esp() {
  [[ ${OMARCHY_BOOT_TEST:-} == "1" ]] && return 0
  [[ $(stat -f -c %T "$ESP" 2>/dev/null) == "msdos" ]] || die "the EFI system partition is not mounted at $ESP"
  [[ $(stat -f -c %T "$BOOT" 2>/dev/null) == "msdos" ]] || die "the boot partition is not mounted at $BOOT"
  # Named by the caller, the two must still be two filesystems.
  [[ $BOOT == "$ESP" || $(stat -c %d "$BOOT") != "$(stat -c %d "$ESP")" ]] ||
    die "$BOOT is the same filesystem as the ESP at $ESP, not an XBOOTLDR partition beside it"
  # And what fstab, the mounts and the partition types say, as on a running
  # system: an ESP at /efi or /boot, or one beside the XBOOTLDR partition on its disk.
  if [[ $BOOT != "$ESP" || $ESP == /efi || $ESP == /boot ]]; then
    omarchy-boot-partitions --expect "$ESP" "$BOOT" >/dev/null || die "the boot partitions aren't the ones named ($ESP, $BOOT)"
  fi
}

# The btrfs top level, where @, its snapshots and the store live side by side.
# Mounted on its own so this works the same from the live system and from a
# booted snapshot, whose / is an overlay.
# The root whose kernels are published: the live root @, even from a booted
# snapshot, or the root a factory reset is building
# (omarchy-boot-switch install sets OMARCHY_BOOT_LIVE_ROOT=/ in its chroot).
LIVE_ROOT_OVERRIDE=${OMARCHY_BOOT_LIVE_ROOT:-}

live_root() {
  echo "${LIVE_ROOT_OVERRIDE:-$TOP/@}"
}

mount_top() {
  [[ ${OMARCHY_BOOT_TEST:-} == "1" ]] && return 0
  mountpoint -q "$TOP" && return 0
  local device
  device=$(findmnt -n -o SOURCE --mountpoint "$STORE")
  device=${device%%\[*}
  mkdir -p "$TOP"
  mount -t btrfs -o subvolid=5 "$device" "$TOP" || die "could not mount the btrfs top level of $device"
}

with_lock() {
  mkdir -p "$(dirname "$LOCK")"
  exec 9>"$LOCK"
  flock -w "${OMARCHY_BOOT_LOCK_WAIT:-300}" 9 || die "another boot image update is still running"
}

# --- command lines -------------------------------------------------------------

# /etc/kernel/cmdline (the root and encryption parameters the installer
# wrote), Omarchy's defaults, then every /etc/cmdline.d/*.conf in name order,
# comments dropped, as one line. An /etc/cmdline.d/omarchy-defaults.conf
# replaces the packaged defaults.
# OMARCHY_PATH has a default: this runs as root from units and pacman hooks,
# outside the session that sets it.
assemble_cmdline() {
  local root=${1:-/} file defaults=${OMARCHY_BOOT_CMDLINE_DEFAULTS:-${OMARCHY_PATH:-/usr/share/omarchy}/default/boot/cmdline-defaults.conf}
  [[ -f $root/etc/cmdline.d/omarchy-defaults.conf ]] && defaults=
  {
    # No drop-ins, or one of only comments, is no failure under errexit and
    # pipefail: each step succeeds whether or not it prints anything.
    if [[ -f $root/etc/kernel/cmdline ]]; then cat "$root/etc/kernel/cmdline"; fi
    if [[ -n $defaults && -f $defaults ]]; then grep -v '^[[:space:]]*#' "$defaults" || true; fi
    for file in "$root"/etc/cmdline.d/*.conf; do
      if [[ -f $file ]]; then grep -v '^[[:space:]]*#' "$file" || true; fi
    done
  } | tr -s '[:space:]' ' ' | sed 's/^ //; s/ $//'
}

# Points rootflags=...subvol= at another subvolume, keeping the other options.
# Refuses command lines it cannot rewrite safely.
cmdline_with_subvol() {
  local cmdline=$1 subvol=$2 token out=() found=0 opts
  for token in $cmdline; do
    case $token in
    rootflags=*)
      opts=${token#rootflags=}
      [[ ,$opts, != *,subvolid=* ]] || die "the command line selects the root by subvolid=, which a snapshot entry cannot override"
      if [[ ,$opts, == *,subvol=* ]]; then
        opts=$(sed -E "s#(^|,)subvol=[^,]*#\1subvol=$subvol#" <<<"$opts")
        out+=("rootflags=$opts")
        found=1
      else
        out+=("$token")
      fi
      ;;
    *) out+=("$token") ;;
    esac
  done
  ((found)) || die "the command line has no rootflags=subvol= to point at a snapshot"
  echo "${out[*]}"
}

cmdline_without() {
  local cmdline=$1 key=$2 token out=()
  for token in $cmdline; do
    [[ $token == "$key" || $token == "$key="* ]] || out+=("$token")
  done
  echo "${out[*]}"
}

cmdline_with_secure_boot() {
  local cmdline=$1 token tokens=() kernel=() init=()
  local IFS=$' \t\n'
  read -ra tokens <<<"$cmdline"
  for token in "${tokens[@]}"; do
    if ((${#init[@]})) || [[ $token == "--" ]]; then
      init+=("$token")
    else
      case $token in
      lockdown | lockdown=* | iommu.passthrough | iommu.passthrough=* | intel_iommu | intel_iommu=* | sysctl.kernel.kexec_load_disabled | sysctl.kernel.kexec_load_disabled=*) ;;
      *) kernel+=("$token") ;;
      esac
    fi
  done
  read -ra tokens <<<"$SECURE_BOOT_SWITCHES"
  kernel+=("${tokens[@]}" "${init[@]}")
  echo "${kernel[*]}"
}

# --- images ----------------------------------------------------------------------

image_dir() { echo "$STORE/images/$1"; }
image_get() { kv_get "$STORE/images/$1/manifest" "$2"; }

current_image() {
  local link=$STORE/current/$1
  [[ -L $link ]] && basename "$(readlink "$link")"
  return 0
}

previous_image() {
  local link=$STORE/previous/$1
  [[ -L $link ]] && basename "$(readlink "$link")"
  return 0
}

# Installed kernels of a root: those whose modules.builtin the root's database says a package
# owns, not the copy kernel-modules-hook restores. Nothing owned means it can't tell: keep all.
root_kernels() {
  local root=$1 pkgbase dir all=() owned=() db=()
  [[ ${root%/} == "" ]] || db=(--dbpath "${root%/}/var/lib/pacman")
  for pkgbase in "${root%/}"/usr/lib/modules/*/pkgbase; do
    [[ -f $pkgbase ]] || continue
    dir=${pkgbase%/pkgbase}
    all+=("$(<"$pkgbase") ${dir##*/}")
    if pacman --root "$root" "${db[@]}" -Qo -- "$dir/modules.builtin" &>/dev/null; then owned+=("${all[-1]}"); fi
  done
  ((${#owned[@]})) || owned=("${all[@]}")
  ((${#owned[@]} == 0)) || printf '%s\n' "${owned[@]}" | sort -u
}

preferred_kernel() {
  local preferred
  preferred=$(state_get preferred)
  if [[ -n $preferred && -L $STORE/current/$preferred ]]; then
    echo "$preferred"
  else
    # Among the kernels with a current image.
    local kernels
    kernels=$(root_kernels "${1:-/}" | awk '{ print $1 }' | while read -r k; do
      [[ -L $STORE/current/$k || ! -d $STORE/current ]] && echo "$k"
    done)
    grep -x linux-omarchy <<<"$kernels" || sed -n 1p <<<"$kernels"
  fi
}

# A kernel that is no longer installed loses its current image: its live entry
# goes, and snapshots pinned to the image keep booting it. A kernel upgrade
# removes the old version's vmlinuz too, so this runs after the transaction,
# when the upgraded kernel is installed again. A root that shows no kernels at
# all is a mount gone wrong, not a machine without any.
prune_current() {
  local kernels link
  kernels=$(root_kernels "$1" | awk '{ print $1 }')
  [[ -n $kernels ]] || return 0
  for link in "$STORE"/current/*; do
    [[ -L $link ]] || continue
    if ! grep -qxF "$(basename "$link")" <<<"$kernels"; then
      rm -f "$link"
      log "$(basename "$link") is no longer installed; its live entry goes"
    fi
  done
}

cmd_import() {
  (($# == 4)) || die "usage: import PKGBASE KVER VMLINUZ INITRAMFS"
  local pkgbase=$1 kver=$2 vmlinuz=$3 initramfs=$4 cmdline hash image dir
  [[ -s $vmlinuz && -s $initramfs ]] || die "import: missing kernel or initramfs for $pkgbase"
  cmdline=$(assemble_cmdline "${OMARCHY_BOOT_CMDLINE_ROOT:-/}")
  [[ $cmdline == *root=* ]] || die "import: /etc/kernel/cmdline names no root="
  hash=$( { sha256sum <"$vmlinuz"; sha256sum <"$initramfs"; printf '%s' "$cmdline"; } | sha256sum | cut -c1-12)
  image=$pkgbase-$hash
  dir=$(image_dir "$image")

  if [[ ! -d $dir ]]; then
    rm -rf "$dir.new"
    mkdir -p "$dir.new"
    cp --reflink=auto "$vmlinuz" "$dir.new/vmlinuz"
    cp --reflink=auto "$initramfs" "$dir.new/initramfs.img"
    {
      echo "PKGBASE=$pkgbase"
      echo "KVER=$kver"
      echo "CMDLINE=$cmdline"
      echo "CREATED=$(date -u +%Y-%m-%dT%H:%M:%SZ)"
    } >"$dir.new/manifest"
    sync "$dir.new/vmlinuz" "$dir.new/initramfs.img" "$dir.new/manifest" "$dir.new" 2>/dev/null || true
    mv "$dir.new" "$dir"
    sync "$(dirname "$dir")" 2>/dev/null || true
  fi

  mkdir -p "$STORE/current"
  ln -sfn "../images/$image" "$STORE/current/.$pkgbase.new"
  mv -T "$STORE/current/.$pkgbase.new" "$STORE/current/$pkgbase"
  sync "$STORE/current" 2>/dev/null || true
  log "boot image for $pkgbase $kver is $image"
}

# Same kernel and initramfs under another command line, for a restored root
# whose swapfile moved since its image was built.
derive_image() {
  local source=$1 cmdline=$2 hash image dir
  hash=$( { sha256sum <"$(image_dir "$source")/vmlinuz"; sha256sum <"$(image_dir "$source")/initramfs.img"; printf '%s' "$cmdline"; } | sha256sum | cut -c1-12)
  image=$(image_get "$source" PKGBASE)-$hash
  dir=$(image_dir "$image")
  if [[ ! -d $dir ]]; then
    rm -rf "$dir.new"
    mkdir -p "$dir.new"
    cp --reflink=auto "$(image_dir "$source")/vmlinuz" "$(image_dir "$source")/initramfs.img" "$dir.new/"
    { grep -v '^CMDLINE=' "$(image_dir "$source")/manifest" || true; printf 'CMDLINE=%s\n' "$cmdline"; } >"$dir.new/manifest"
    sync "$dir.new/vmlinuz" "$dir.new/initramfs.img" "$dir.new/manifest" "$dir.new" 2>/dev/null || true
    mv "$dir.new" "$dir"
    sync "$(dirname "$dir")" 2>/dev/null || true
  fi
  echo "$image"
}

# --- snapshots ---------------------------------------------------------------------

# The live root's snapshots: @'s, or those of the root a factory reset builds,
# never the old owner's.
snapshots_dir() { echo "$(live_root)/.snapshots"; }

cmd_pin() {
  (($# == 1)) && [[ $1 =~ ^[0-9]+$ ]] || die "usage: pin NUMBER"
  local num=$1 dir pkgbase image kver
  dir=$(snapshots_dir)/$num
  [[ -d $dir/snapshot ]] || die "pin: snapshot $num does not exist"

  # The image of the kernel the machine boots by default, when that kernel is
  # in the snapshot; otherwise any installed kernel the snapshot carries.
  for pkgbase in $(preferred_kernel "$(live_root)") $(ls "$STORE/current" 2>/dev/null); do
    image=$(current_image "$pkgbase")
    [[ -n $image ]] || continue
    kver=$(image_get "$image" KVER)
    if [[ -d $dir/snapshot/usr/lib/modules/$kver ]]; then
      printf '%s\n' "$image" >"$dir/.omarchy-boot-image.new"
      sync "$dir/.omarchy-boot-image.new" 2>/dev/null || true
      mv -f "$dir/.omarchy-boot-image.new" "$dir/omarchy-boot-image"
      sync "$dir" 2>/dev/null || true
      log "pinned snapshot $num to $image"
      return 0
    fi
  done
  die "pin: no stored boot image matches a kernel in snapshot $num"
}

info_field() {
  sed -n "s:.*<$2>\(.*\)</$2>.*:\1:p" "$1" | sed -n 1p
}

# Snapshot numbers with a pin whose image still exists, newest first.
bootable_snapshots() {
  local dir num image
  {
    for dir in "$(snapshots_dir)"/*/; do
      num=$(basename "$dir")
      [[ $num =~ ^[0-9]+$ && -f $dir/omarchy-boot-image && -d $dir/snapshot ]] || continue
      image=$(<"$dir/omarchy-boot-image")
      if [[ -d $(image_dir "$image") ]]; then
        echo "$num"
      fi
    done | sort -rn | awk -v max="$MAX_SNAPSHOTS" 'NR <= max'
    # Keep an unfinished switch's recovery snapshot published across retries
    # even if newer snapshots push it past MAX_SNAPSHOTS.
    num=$(state_get recovery_snapshot)
    if [[ $(state_get phase) != "active" && $num =~ ^[0-9]+$ && -f $(snapshots_dir)/$num/omarchy-boot-image && -d $(snapshots_dir)/$num/snapshot ]]; then
      image=$(<"$(snapshots_dir)/$num/omarchy-boot-image")
      if [[ -d $(image_dir "$image") ]]; then
        echo "$num"
      fi
    fi
  } | sort -rnu
}

snapshot_details() {
  local info=$1 desc date
  desc=$(info_field "$info" description)
  date=$(info_field "$info" date)
  date=$(date -d "$date UTC" '+%b %-d %H:%M' 2>/dev/null || echo "$date")
  echo "${desc:-no description} · $date"
}

# --- building ------------------------------------------------------------------------

osrel() { # pretty-name order
  printf 'NAME="Armbian"\nID=omarchy\nIMAGE_ID=omarchy\nPRETTY_NAME="%s"\nIMAGE_VERSION=%s\n' "$1" "$2"
}

# One profile per line of the profile list: ID, PRETTY, TITLE, ORDER, CMDLINE
# separated by the ASCII unit separator (\x1f). Not tabs: read collapses runs
# of whitespace separators, so an empty TITLE would shift the fields.

# What an image reads besides its manifest and profiles: uki.conf and every
# file it names, such as a Snapdragon machine's device trees. Part of the
# published image's key, so a changed tree reaches the next boot.
uki_inputs() {
  local path hwids=$HWIDS/x64
  omarchy-hw-aarch64 && hwids=$HWIDS/aa64
  # ukify reads the hardware IDs here even when uki.conf doesn't name them.
  if [[ -d $hwids ]]; then find -L "$hwids" -type f -exec sha256sum {} + | sort; fi
  [[ -r $UKI_CONFIG ]] || return 0
  cat "$UKI_CONFIG"
  while read -r path; do
    if [[ -f $path ]]; then
      sha256sum "$path"
    elif [[ -d $path ]]; then
      find -L "$path" -type f -exec sha256sum {} + | sort
    fi
  done < <(sed -n 's/^[^#=]*=//p' "$UKI_CONFIG" | grep -o '/[^[:space:]]*' || true)
}
build_work_dir() {
  local dir=$1 need tmp_free
  need=$(( ($(stat -c %s "$dir/vmlinuz") + $(stat -c %s "$dir/initramfs.img")) * 2 + 64 * 1024 * 1024 ))
  tmp_free=$(df --output=avail -B1 /tmp 2>/dev/null | tail -1 || true)
  if [[ -w /tmp && $tmp_free =~ ^[0-9]+$ ]] && ((tmp_free > need)); then
    mktemp -d /tmp/omarchy-boot-build.XXXXXX
  else
    mktemp -d "$STORE/tmp/build.XXXXXX"
  fi
}

# The published entry filename loader.conf currently names (without @profile).
loader_default_file() {
  local conf=$ESP/loader/loader.conf def
  [[ -r $conf ]] || return 0
  def=$(sed -nE 's/^default[[:space:]]+([^[:space:]]+).*/\1/p' "$conf" | tail -1)
  echo "${def%%@*}"
}

# Make room on $BOOT for a staging UKI by removing stale staging files and
# superseded UKIs of this machine (never a wanted image, the active
# loader.conf default, or an armed one-shot entry). Removes nothing unless
# reclaiming can free enough space to satisfy NEED bytes.
reclaim_uki_space() {
  local need=$1 ns=$2 free reclaimable=0 candidate base size
  local -a stale=()
  free=$(df --output=avail -B1 "$BOOT" | tail -1)
  if ((free > need)); then
    return 0
  fi

  for candidate in "$BOOT"/EFI/Linux/omarchy-"$ns"-*.efi.new "$BOOT"/EFI/Linux/omarchy-"$ns"-*.efi; do
    [[ -e $candidate ]] || continue
    base=$(basename "$candidate")
    if [[ $candidate != *.new ]]; then
      [[ ${OMARCHY_BOOT_DEFER_DEFAULT:-} != "1" ]] || continue
      [[ -z ${wanted[$base]:-} && $base != "${cur_default_file:-}" ]] || continue
    fi
    size=$(stat -c %s "$candidate" 2>/dev/null || echo 0)
    stale+=("$candidate")
    reclaimable=$((reclaimable + size))
  done

  if ((free + reclaimable <= need)); then
    return 0
  fi

  for candidate in "${stale[@]}"; do
    base=$(basename "$candidate")
    rm -f "$candidate"
    if [[ $candidate != *.new ]]; then
      rm -f "$STORE/published/$base.key"
    fi
    log "removed $base"
    sync "$BOOT/EFI/Linux" 2>/dev/null || true
    free=$(df --output=avail -B1 "$BOOT" | tail -1)
    if ((free > need)); then
      return 0
    fi
  done
}

build_uki() {
  local image=$1 profiles=$2 out=$3 work dir kver id pretty title order cmdline n=0
  dir=$(image_dir "$image")
  kver=$(image_get "$image" KVER)
  work=$(build_work_dir "$dir")
  BUILD_WORK=$work

  : >"$work/empty.conf"
  local args=(build --linux="$dir/vmlinuz" --initrd="$dir/initramfs.img" --uname="$kver")
  if [[ -r $UKI_CONFIG ]]; then
    args+=(--config="$UKI_CONFIG")
  else
    args+=(--config="$work/empty.conf")
  fi

  # The first profile is built into the image itself: its .profile, .osrel and
  # .cmdline are the shared base, so it is profile 0, the entry named after the
  # file. Joining every profile instead would make ukify add a base profile of
  # its own ("main") in front of them.
  while IFS=$'\x1f' read -r id pretty title order cmdline; do
    [[ -n $id ]] || continue
    n=$((n + 1))
    { echo "ID=$id"; if [[ -n $title ]]; then echo "TITLE=$title"; fi; } >"$work/profile-$n"
    osrel "$pretty" "$order" >"$work/osrel-$n"
    printf '%s' "$cmdline" >"$work/cmdline-$n"
    if ((n == 1)); then
      args+=(--profile="@$work/profile-$n" --os-release="@$work/osrel-$n" --cmdline="@$work/cmdline-$n")
    else
      ukify build --config="$work/empty.conf" --profile="@$work/profile-$n" --os-release="@$work/osrel-$n" \
        --cmdline="@$work/cmdline-$n" --output="$work/profile-$n.efi" >/dev/null
      args+=(--join-profile="$work/profile-$n.efi")
    fi
  done <<<"$profiles"

  if [[ $(state_get signing) == "required" ]]; then
    local key=$STORE/keys/db.key cert=$STORE/keys/db.crt
    [[ -f $key && -f $cert ]] || die "signing is required but $STORE/keys has no key; keeping the published images"
    args+=(--signtool=systemd-sbsign --no-sign-kernel --secureboot-private-key="$key" --secureboot-certificate="$cert")
  fi

  ukify "${args[@]}" --output="$work/uki.efi" >/dev/null || die "ukify could not build $image"
  [[ -s $work/uki.efi ]] || die "ukify wrote no image for $image"

  # Stage beside the old file and rename over it, so a crash never leaves a
  # half-written image as the entry the machine boots.
  rm -f "$out.new"
  local free need
  free=$(df --output=avail -B1 "$BOOT" | tail -1)
  need=$(($(stat -c %s "$work/uki.efi") + 8 * 1024 * 1024))
  if ((free <= need)); then
    reclaim_uki_space "$need" "$(namespace)"
    free=$(df --output=avail -B1 "$BOOT" | tail -1)
  fi
  ((free > need)) || die "$BOOT has $((free / 1024 / 1024)) MB free, $((need / 1024 / 1024)) MB needed; keeping the published images"
  BUILD_STAGED=$out.new
  cp "$work/uki.efi" "$out.new"
  sync "$out.new"
  mv -f "$out.new" "$out"
  BUILD_STAGED=""
  sync "$(dirname "$out")"
  rm -rf "$work"
  BUILD_WORK=""
}

# --- secure boot (Type 1) --------------------------------------------------------------

# Type 1 entries and the kernels they name go on $BOOT, as UKIs do: an entry's
# paths are relative to the partition it is on (Boot Loader Specification), and
# only the signed loader and loader.conf are the ESP's.

verify_ca_cert() {
  ((CA_VERIFIED)) && return 0
  [[ -r $CA_PEM && $CA_SHA256 =~ ^[0-9a-f]{64}$ ]] || return 1
  local got
  got=$(openssl x509 -in "$CA_PEM" -outform DER 2>/dev/null | sha256sum | awk '{print $1}')
  # shellcheck disable=SC2053 # CA_SHA256 is validated 64-char hex above.
  [[ $got == $CA_SHA256 ]] || return 1
  CA_VERIFIED=1
}

# Type 1 Secure Boot signs the loader and kernel with the pinned Omarchy Root CA.
# The locally built initramfs and entry options stay separate (measured into TPM
# PCR 9 and PCR 12 at boot), matching standard desktop Linux Secure Boot.
verify_signed_efi() {
  local file=$1
  omarchy-cmd-present sbverify || die "sbsigntools is required to verify Secure Boot binaries (sbverify not found)"
  [[ -s $file ]] || return 1
  verify_ca_cert || return 1
  sbverify --cert "$CA_PEM" "$file" >/dev/null 2>&1 || return 1
  ! sbverify --list "$file" 2>/dev/null | grep -qx 'signature 2'
}

install_esp_file() {
  local src=$1 dst=$2 dir free need
  dir=$(dirname "$dst")
  mkdir -p "$dir"
  if [[ -f $dst ]] && cmp -s "$src" "$dst"; then
    return 0
  fi
  free=$(df --output=avail -B1 "$dir" | tail -1)
  need=$(($(stat -c %s "$src") + 8 * 1024 * 1024))
  ((free > need)) || die "$dir has $((free / 1024 / 1024)) MB free, $((need / 1024 / 1024)) MB needed; keeping the published images"
  cp "$src" "$dst.new"
  sync "$dst.new"
  mv -f "$dst.new" "$dst"
  sync "$dir"
}

sync_signed_loader() {
  verify_signed_efi "$SIGNED_LOADER" ||
    die "signed systemd-boot loader is missing or not trusted by $CA_PEM ($SIGNED_LOADER)"
  install_esp_file "$SIGNED_LOADER" "$ESP/EFI/systemd/systemd-bootx64.efi"
  if fallback_ours "$ESP/EFI/BOOT/BOOTX64.EFI"; then
    install_esp_file "$SIGNED_LOADER" "$ESP/EFI/BOOT/BOOTX64.EFI"
  fi
}

# The firmware's fallback loader is Omarchy's only on an ESP of its own: never
# beside an XBOOTLDR partition, never where Windows' boot manager is, whatever
# decided the layout, and only over nothing or a systemd-boot or Limine there.
fallback_ours() {
  [[ $BOOT == "$ESP" && ! -e $ESP/EFI/Microsoft ]] || return 1
  [[ ! -f $1 ]] || grep -qaE 'systemd-boot|[Ll]imine' "$1"
}

set_loader_editor_no() {
  [[ ${OMARCHY_BOOT_DEFER_DEFAULT:-} == "1" ]] && return 0
  local conf=$ESP/loader/loader.conf tmp
  mkdir -p "$(dirname "$conf")"
  tmp=$(mktemp "$conf.XXXXXX")
  { grep -v '^editor ' "$conf" 2>/dev/null || true; echo "editor no"; } >"$tmp"
  if cmp -s "$tmp" "$conf"; then
    rm -f "$tmp"
  else
    sync "$tmp" 2>/dev/null || true
    mv -f "$tmp" "$conf"
    sync "$(dirname "$conf")" 2>/dev/null || true
  fi
}

type1_conf_name() {
  local ns=$1 image=$2 pid=$3
  if [[ $pid == "omarchy" ]]; then
    echo "omarchy-$ns-$image.conf"
  else
    echo "omarchy-$ns-$image-$pid.conf"
  fi
}

type1_conf_image_dir() {
  local ns=$1 conf=$2
  [[ -r $conf ]] || return 0
  sed -nE "s|^linux[[:space:]]+/omarchy-$ns/([^/]+)/vmlinuz$|\1|p" "$conf" | sed -n 1p
}

publish_type1_image() {
  local ns=$1 image=$2
  local src_dir dst_dir
  src_dir=$(image_dir "$image")
  dst_dir=$BOOT/omarchy-$ns/$image
  install_esp_file "$src_dir/vmlinuz" "$dst_dir/vmlinuz"
  install_esp_file "$src_dir/initramfs.img" "$dst_dir/initramfs.img"
}

publish_type1_conf() {
  local ns=$1 image=$2 pid=$3 title=$4 kver=$5 cmdline=$6
  local name conf tmp content
  name=$(type1_conf_name "$ns" "$image" "$pid")
  conf=$BOOT/loader/entries/$name
  mkdir -p "$BOOT/loader/entries"
  content=$(
    printf 'title   %s
' "$title"
    printf 'version %s
' "$kver"
    printf 'linux   /omarchy-%s/%s/vmlinuz
' "$ns" "$image"
    printf 'initrd  /omarchy-%s/%s/initramfs.img
' "$ns" "$image"
    printf 'options %s
' "$cmdline"
  )
  if [[ -f $conf ]] && cmp -s <(printf '%s
' "$content") "$conf"; then
    return 0
  fi
  tmp=$(mktemp "$conf.XXXXXX")
  printf '%s
' "$content" >"$tmp"
  sync "$tmp"
  mv -f "$tmp" "$conf"
  sync "$BOOT/loader/entries"
  log "wrote Type 1 entry $name"
}

render_secure_boot_entries() {
  local ns=$1 preferred=$2 restoring=$3
  local live next_prev last_pub image sorted pid pretty ptitle cmdline kver conf_name file id
  local -A wanted_img=() wanted_conf=()
  local entries=()

  live=$(current_image "$preferred")
  [[ -n $live && -d $(image_dir "$live") ]] || die "no boot image stored for $preferred; run omarchy-boot-rebuild"
  verify_signed_efi "$(image_dir "$live")/vmlinuz" ||
    die "refusing to publish unsigned kernel $(image_dir "$live")/vmlinuz while Secure Boot is enabled"
  verify_signed_efi "$SIGNED_LOADER" ||
    die "signed systemd-boot loader is missing or not trusted by $CA_PEM ($SIGNED_LOADER)"
  if [[ ${OMARCHY_BOOT_DEFER_DEFAULT:-} != "1" ]]; then
    sync_signed_loader
  fi

  # Render every planned profile whose image is signed by our CA; fail closed if
  # a pending restore's image is unsigned.
  for image in "${!profiles[@]}"; do
    if ! verify_signed_efi "$(image_dir "$image")/vmlinuz"; then
      if ((restoring)) && grep -qE $'^omarchy-restore(d)?' <<<"${profiles[$image]}"; then
        die "refusing to publish unsigned restore image $image while Secure Boot is enabled"
      fi
      continue
    fi
    publish_type1_image "$ns" "$image"
    wanted_img[$image]=1
    kver=$(image_get "$image" KVER)
    sorted=$(printf '%s' "${profiles[$image]}" | sort -t$'' -k4,4nr)
    while IFS=$'' read -r pid pretty ptitle _ cmdline; do
      [[ -n $pid ]] || continue
      conf_name=$(type1_conf_name "$ns" "$image" "$pid")
      publish_type1_conf "$ns" "$image" "$pid" "${pretty}${ptitle:+ ($ptitle)}" "$kver" "$(cmdline_with_secure_boot "$cmdline")"
      wanted_conf[$conf_name]=1
      entries+=("$(printf '%s	%s	%s%s' "$pid" "$conf_name" "$pretty" "${ptitle:+ ($ptitle)}")")
    done <<<"$sorted"
  done

  # Determine fallback signed kernel (either last successfully published live
  # image or existing previous link) and publish it BEFORE rotating state.
  last_pub=$(state_get "last_signed_$preferred")
  next_prev=$(previous_image "$preferred")
  if [[ -n $last_pub && $last_pub != "$live" && -d $(image_dir "$last_pub") ]] && verify_signed_efi "$(image_dir "$last_pub")/vmlinuz"; then
    next_prev=$last_pub
  fi
  if [[ -n $next_prev && $next_prev != "$live" && -d $(image_dir "$next_prev") ]] && verify_signed_efi "$(image_dir "$next_prev")/vmlinuz"; then
    publish_type1_image "$ns" "$next_prev"
    wanted_img[$next_prev]=1
    kver=$(image_get "$next_prev" KVER)
    conf_name=$(type1_conf_name "$ns" "$next_prev" "previous")
    publish_type1_conf "$ns" "$next_prev" "previous" "Omarchy (previous)" "$kver" "$(cmdline_with_secure_boot "$(image_get "$next_prev" CMDLINE)")"
    wanted_conf[$conf_name]=1
    entries+=("$(printf 'omarchy-previous	%s	Omarchy (previous — %s)' "$conf_name" "$kver")")
  fi

  printf '%s
' "${entries[@]}" | sort >"$STORE/entries.new"
  mv -f "$STORE/entries.new" "$STORE/entries"

  # Update restore journal / one-shot and loader.conf BEFORE deleting old entries
  # or rotating previous/last_signed state.
  local oneshot
  oneshot=$(efivar_string LoaderEntryOneShot)
  if ((restoring)); then
    local journal=$STORE/restore/journal
    id=$(entry_id omarchy-restored)
    if [[ -n $id && $id != "$(kv_get "$journal" ONESHOT)" ]]; then
      kv_set "$journal" ONESHOT "$id"
    fi
    id=$(entry_id omarchy-restore)
    if [[ $(kv_get "$journal" STATE) == "pending" && -n $id && $oneshot == *omarchy-restore* && $oneshot != "$id" ]]; then
      bootctl set-oneshot "$id" >/dev/null 2>&1 || log "could not arm the restore's maintenance boot ($id)" >&2
    fi
  fi

  set_loader_editor_no
  set_loader_default "$(type1_conf_name "$ns" "$live" omarchy)"

  # Commit fallback rotation and cleanup only when not staging a deferred/override transition.
  if [[ -z $MODE_OVERRIDE ]]; then
    if [[ ${OMARCHY_BOOT_DEFER_DEFAULT:-} != "1" ]]; then
      if [[ -n $next_prev && $next_prev != "$live" && -d $(image_dir "$next_prev") ]]; then
        mkdir -p "$STORE/previous"
        ln -sfn "../images/$next_prev" "$STORE/previous/.$preferred.new"
        mv -T "$STORE/previous/.$preferred.new" "$STORE/previous/$preferred"
        sync "$STORE/previous"
      fi
      state_set "last_signed_$preferred" "$live"
    fi

    local cur_default="" keep_conf keep_dir
    if [[ ${OMARCHY_BOOT_DEFER_DEFAULT:-} == "1" ]]; then
      cur_default=$(sed -n 's/^default //p' "$ESP/loader/loader.conf" 2>/dev/null | tail -1 || true)
    fi
    for keep_conf in "$oneshot" "$cur_default"; do
      [[ $keep_conf == omarchy-"$ns"-*.conf ]] || continue
      wanted_conf[$keep_conf]=1
      keep_dir=$(type1_conf_image_dir "$ns" "$BOOT/loader/entries/$keep_conf")
      [[ -n $keep_dir ]] && wanted_img[$keep_dir]=1
    done

    for file in "$BOOT"/loader/entries/omarchy-"$ns"-*.conf "$BOOT"/loader/entries/omarchy-"$ns"-*.conf.*; do
      [[ -e $file ]] || continue
      if [[ -z ${wanted_conf[$(basename "$file")]:-} ]]; then
        rm -f "$file"
        log "removed $(basename "$file")"
      fi
    done
    for file in "$BOOT"/omarchy-"$ns"/*; do
      [[ -e $file ]] || continue
      if [[ -z ${wanted_img[$(basename "$file")]:-} ]]; then
        rm -rf "$file"
        log "removed Type 1 directory $(basename "$file")"
      fi
    done
    for file in "$BOOT"/EFI/Linux/omarchy-"$ns"-*.efi "$BOOT"/EFI/Linux/omarchy-"$ns"-*.efi.new; do
      [[ -e $file ]] || continue
      if [[ -n $oneshot && $(basename "$file") == "${oneshot%%@*}" ]]; then
        continue
      fi
      if [[ -n $cur_default && $(basename "$file") == "${cur_default%%@*}" ]]; then
        continue
      fi
      rm -f "$file" "$STORE/published/$(basename "$file").key"
      log "removed $(basename "$file")"
    done
    gc_images
  fi
}

# --- sync ------------------------------------------------------------------------------

cmd_sync() {
  check_store
  check_esp
  mount_top
  mkdir -p "$STORE/tmp" "$STORE/published" "$BOOT/EFI/Linux"
  rm -rf "$STORE"/tmp/build.*
  # Boot images no longer carry a splash; a store from before keeps none.
  rm -f "$STORE/splash.bmp"

  local ns preferred pkgbase kver image num dir file id
  local -A profiles=() wanted=()
  local entries=()
  ns=$(namespace)
  prune_current "$(live_root)"
  preferred=$(preferred_kernel "$(live_root)")

  # The live system: one profile per installed kernel with a stored image.
  local order=999999
  while read -r pkgbase kver; do
    image=$(current_image "$pkgbase")
    if [[ -z $image ]]; then
      log "no boot image stored for $pkgbase $kver; run omarchy-boot-rebuild"
      continue
    fi
    local pretty=Omarchy
    [[ $pkgbase == "$preferred" ]] || pretty="Omarchy ($pkgbase)"
    local this_order=$order
    [[ $pkgbase == "$preferred" ]] && this_order=1000000
    profiles[$image]+=$(printf 'omarchy\x1f%s\x1f\x1f%s\x1f%s' "$pretty" "$this_order" "$(image_get "$image" CMDLINE)")$'\n'
    order=$((order - 1))
  done < <(root_kernels "$(live_root)")

  # A pending restore adds the maintenance boot that swaps the roots and the
  # entry that boots the restored root once it is in place.
  local journal=$STORE/restore/journal restoring=0
  if [[ -f $journal ]] && [[ $(kv_get "$journal" STATE) =~ ^(pending|swapping|swapped)$ ]]; then
    local tx restored live_image
    tx=$(kv_get "$journal" TX)
    restored=$(kv_get "$journal" IMAGE)
    live_image=$(current_image "$preferred")
    if [[ -n $live_image && -d $(image_dir "$restored") ]]; then
      profiles[$live_image]+=$(printf 'omarchy-restore\x1fRestoring a snapshot\x1f\x1f0\x1f%s' \
        "$(image_get "$live_image" CMDLINE) noresume omarchy.restore=$tx")$'\n'
      profiles[$restored]+=$(printf 'omarchy-restored\x1fOmarchy (restored)\x1f\x1f0\x1f%s' "$(image_get "$restored" CMDLINE)")$'\n'
      restoring=1
    fi
  fi

  # Snapshots, newest first, each on the image it was pinned to.
  for num in $(bootable_snapshots); do
    dir=$(snapshots_dir)/$num
    image=$(<"$dir/omarchy-boot-image")
    profiles[$image]+=$(printf 'snapshot-%s\x1fSnapshot %s\x1f%s\x1f%s\x1f%s' "$num" "$num" \
      "$(snapshot_details "$dir/info.xml")" "$num" \
      "$(cmdline_with_subvol "$(cmdline_without "$(image_get "$image" CMDLINE)" resume) noresume" "@/.snapshots/$num/snapshot")")$'\n'
  done

  # The root a restore replaced, bootable to undo it.
  local backup backup_image
  backup=$(state_get backup)
  backup_image=$(state_get backup_image)
  if [[ -n $backup && -d $TOP/$backup && -d $(image_dir "${backup_image:-none}") ]]; then
    profiles[$backup_image]+=$(printf 'backup\x1fBefore restore\x1f%s\x1f0\x1f%s' "$(state_get backup_date)" \
      "$(cmdline_with_subvol "$(cmdline_without "$(image_get "$backup_image" CMDLINE)" resume) noresume" "$backup")")$'\n'
  fi

  if [[ $(effective_secure_boot) == "enabled" ]]; then
    render_secure_boot_entries "$ns" "$preferred" "$restoring"
    return 0
  fi

  # The entry a pending one-shot boot points at stays until it has booted,
  # and the active loader.conf default stays until loader.conf moves past it.
  local oneshot oneshot_file cur_default_file live live_file
  oneshot=$(efivar_string LoaderEntryOneShot)
  oneshot_file=${oneshot%%@*}
  cur_default_file=$(loader_default_file)
  live=$(current_image "$preferred")
  live_file=""
  if [[ -n $live ]]; then
    live_file=omarchy-$ns-$live.efi
  fi

  # Pre-populate wanted before building so tight ESPs can reclaim superseded
  # non-default images between builds instead of needing room for all of them
  # at once.
  for image in "${!profiles[@]}"; do
    wanted[omarchy-$ns-$image.efi]=1
  done
  if [[ -n $oneshot_file ]]; then
    wanted[$oneshot_file]=1
  fi

  # Publish the preferred live image first and move loader.conf to it as soon
  # as it is on disk, so the previous default can be reclaimed if secondary
  # kernels need the space on a tight ESP.
  local -a images=() other_images=()
  if [[ -n $live && -n ${profiles[$live]:-} ]]; then
    images+=("$live")
  fi
  if ((${#profiles[@]})); then
    mapfile -t other_images < <(printf '%s\n' "${!profiles[@]}" | sort)
    for image in "${other_images[@]}"; do
      [[ $image == "$live" ]] || images+=("$image")
    done
  fi

  # Live first inside each image: profile 0 is the entry named after the file.
  for image in "${images[@]}"; do
    local sorted key
    sorted=$(printf '%s' "${profiles[$image]}" | sort -t$'\x1f' -k4,4nr)
    file=omarchy-$ns-$image.efi
    key=$(
      {
        echo "format=$FORMAT signing=$(state_get signing)"
        cat "$(image_dir "$image")/manifest"
        echo "$sorted"
        uki_inputs
      } | sha256sum | cut -c1-64
    )
    if [[ ! -s $BOOT/EFI/Linux/$file || $(cat "$STORE/published/$file.key" 2>/dev/null) != "$key" ]]; then
      build_uki "$image" "$sorted" "$BOOT/EFI/Linux/$file"
      echo "$key" >"$STORE/published/$file.key"
      log "wrote $file"
    fi
    if [[ -n $live_file && $file == "$live_file" && ${OMARCHY_BOOT_DEFER_DEFAULT:-} != "1" ]]; then
      set_loader_default "$live_file"
      cur_default_file=$(loader_default_file)
    fi

    local first=1 pid ptitle
    while IFS=$'\x1f' read -r pid pretty ptitle _ _; do
      [[ -n $pid ]] || continue
      if ((first)); then id=$file; else id=$file@$pid; fi
      first=0
      entries+=("$(printf '%s\t%s\t%s%s' "$pid" "$id" "$pretty" "${ptitle:+ ($ptitle)}")")
    done <<<"$sorted"
  done

  if ((${#entries[@]})); then
    printf '%s\n' "${entries[@]}" | sort >"$STORE/entries.new"
  else
    : >"$STORE/entries.new"
  fi
  mv -f "$STORE/entries.new" "$STORE/entries"

  # The restored root's entry is profile 0 of its image or not, depending on
  # the snapshots that image carries, which can change before the reboot: the
  # journal names the one just published, for the maintenance boot to arm.
  if ((restoring)); then
    id=$(entry_id omarchy-restored)
    if [[ -n $id && $id != "$(kv_get "$journal" ONESHOT)" ]]; then
      kv_set "$journal" ONESHOT "$id"
    fi
    # And the maintenance boot the firmware is armed for moves with the live
    # image when that is rebuilt before the reboot. Only that one: a one-shot
    # boot the user chose since (a snapshot) stays theirs.
    id=$(entry_id omarchy-restore)
    if [[ $(kv_get "$journal" STATE) == "pending" && -n $id && $oneshot == *@omarchy-restore && $oneshot != "$id" ]]; then
      bootctl set-oneshot "$id" >/dev/null 2>&1 || log "could not arm the restore's maintenance boot ($id)" >&2
    fi
  fi

  if [[ -n $live_file ]]; then
    set_loader_default "$live_file"
    cur_default_file=$(loader_default_file)
  fi

  local base
  for file in "$BOOT"/EFI/Linux/omarchy-"$ns"-*.efi "$BOOT"/EFI/Linux/omarchy-"$ns"-*.efi.new; do
    [[ -e $file ]] || continue
    base=$(basename "$file")
    if [[ -z ${wanted[$base]:-} && $base != "$cur_default_file" ]]; then
      if [[ ${OMARCHY_BOOT_DEFER_DEFAULT:-} == "1" && $file != *.new ]]; then
        continue
      fi
      rm -f "$file" "$STORE/published/$base.key"
      log "removed $base"
    fi
  done

  # Clean up leftover Type 1 entries only after the default has moved to the UKI
  # (never while OMARCHY_BOOT_DEFER_DEFAULT=1 keeps loader.conf on Type 1), and
  # keep any Type 1 entry still armed as LoaderEntryOneShot.
  if [[ ${OMARCHY_BOOT_DEFER_DEFAULT:-} != "1" ]]; then
    local keep_dir=""
    if [[ $oneshot == omarchy-"$ns"-*.conf ]]; then
      keep_dir=$(type1_conf_image_dir "$ns" "$BOOT/loader/entries/$oneshot")
    fi
    for file in "$BOOT"/loader/entries/omarchy-"$ns"-*.conf "$BOOT"/loader/entries/omarchy-"$ns"-*.conf.new; do
      [[ -e $file ]] || continue
      [[ -n $oneshot && $(basename "$file") == "$oneshot" ]] && continue
      rm -f "$file"
      log "removed $(basename "$file")"
    done
    if [[ -d $BOOT/omarchy-$ns ]]; then
      for file in "$BOOT"/omarchy-"$ns"/*; do
        [[ -e $file ]] || continue
        [[ -n $keep_dir && $(basename "$file") == "$keep_dir" ]] && continue
        rm -rf "$file"
      done
      rmdir "$BOOT/omarchy-$ns" 2>/dev/null || true
    fi
  fi

  gc_images
}

# The published entry id for a profile id (omarchy-restore, snapshot-12, ...).
entry_id() {
  awk -F'\t' -v id="$1" '$1 == id { print $2; exit }' "$STORE/entries" 2>/dev/null
}

efivar_string() {
  local file=${OMARCHY_BOOT_EFIVARS:-/sys/firmware/efi/efivars}/$1-$LOADER_GUID
  [[ -r $file ]] && tail -c +5 "$file" | tr -d '\0'
  return 0
}

# A factory reset builds the next root's images next to the running ones and
# may only hand the firmware's default over once that root is in place:
# OMARCHY_BOOT_DEFER_DEFAULT=1 leaves loader.conf alone and records the
# default in the store, for the reset to write after activating the root.
set_loader_default() {
  local conf=$ESP/loader/loader.conf tmp
  if [[ ${OMARCHY_BOOT_DEFER_DEFAULT:-} == "1" ]]; then
    echo "$1" >"$STORE/pending-default"
    return 0
  fi
  mkdir -p "$(dirname "$conf")"
  tmp=$(mktemp "$conf.XXXXXX")
  { grep -v '^default ' "$conf" 2>/dev/null || true; echo "default $1"; } >"$tmp"
  if cmp -s "$tmp" "$conf"; then
    rm -f "$tmp"
  else
    sync "$tmp" 2>/dev/null || true
    mv -f "$tmp" "$conf"
    sync "$(dirname "$conf")" 2>/dev/null || true
  fi
}

# --- Windows ---------------------------------------------------------------------------

# Each line this sets in loader.conf follows a comment of its own saying so, read
# back to undo exactly that line: the change and its record are one write.
TIMEOUT_MARK="# omarchy-boot-sync: the hidden menu shows while Windows is on this ESP"
# How long the menu shows while Windows is in it, where it was hidden.
WINDOWS_TIMEOUT=5
# Earlier versions set reboot-for-bitlocker themselves, after one of these.
# What they set goes; one the user wrote never does (docs/boot.md).
BITLOCKER_MARKS=(
  "# omarchy-boot-sync: BitLocker's Windows starts through the firmware"
  "# omarchy-boot-sync set for Windows: reboot-for-bitlocker"
)

# Prints file $1 with the line "$2" just before "$3" kept ($4 = keep) or turned
# into the line $5, or dropped where $5 is empty ($4 = undo); a comment no
# longer followed by its line goes either way.
edit_marked() {
  awk -v mark="$2" -v directive="$3" -v mode="$4" -v replacement="${5:-}" '
    held {
      held = 0
      if ($0 == directive) {
        if (mode == "keep") { print mark; print } else if (replacement != "") print replacement
        next
      }
    }
    $0 == mark { held = 1; next }
    { print }
  ' "$1"
}

# Whether file $1 has the line "$2" just before "$3".
marked() {
  awk -v mark="$2" -v directive="$3" 'prev == mark && $0 == directive { found = 1 } { prev = $0 } END { exit !found }' "$1"
}

# systemd-boot lists Windows on its own ESP by itself; while it does, the hidden
# menu shows. Only the one line this set is ever changed back, and a setting
# the user made is never changed.
cmd_windows() {
  local conf=$ESP/loader/loader.conf windows=0 work tmp mark
  [[ $(state_get phase) == "active" && -f $conf ]] || return 0
  check_esp
  [[ -f $ESP/EFI/Microsoft/Boot/bootmgfw.efi ]] && windows=1
  # A private directory, so the edits' scratch files aren't guessable names in /tmp.
  work=$(mktemp -d)
  WINDOWS_WORK=$work
  tmp=$work/loader.conf
  # A last line without its newline would take the next one onto it.
  cat "$conf" >"$tmp"
  [[ ! -s $tmp || $(tail -c 1 "$tmp" | od -An -tx1 | tr -d ' ') == 0a ]] || echo >>"$tmp"

  if ((windows)); then
    edit_marked "$tmp" "$TIMEOUT_MARK" "timeout $WINDOWS_TIMEOUT" keep >"$tmp.new" && mv -f "$tmp.new" "$tmp"
    # Only a lone timeout 0, Omarchy's own, is raised.
    if ! marked "$tmp" "$TIMEOUT_MARK" "timeout $WINDOWS_TIMEOUT" &&
      (($(grep -cE '^[[:space:]]*timeout([[:space:]]|$)' "$tmp" || true) == 1)) && grep -qx 'timeout 0' "$tmp"; then
      awk -v mark="$TIMEOUT_MARK" -v line="timeout $WINDOWS_TIMEOUT" '$0 == "timeout 0" { print mark; print line; next } { print }' "$tmp" >"$tmp.new" &&
        mv -f "$tmp.new" "$tmp"
    fi
  else
    edit_marked "$tmp" "$TIMEOUT_MARK" "timeout $WINDOWS_TIMEOUT" undo "timeout 0" >"$tmp.new" && mv -f "$tmp.new" "$tmp"
  fi
  for mark in "${BITLOCKER_MARKS[@]}"; do
    edit_marked "$tmp" "$mark" "reboot-for-bitlocker yes" undo >"$tmp.new" && mv -f "$tmp.new" "$tmp"
  done

  if cmp -s "$tmp" "$conf"; then
    rm -rf "$work"
    return 0
  fi
  # Staged on the ESP, so the rename over loader.conf stays on one filesystem.
  local staged
  staged=$(mktemp "$conf.XXXXXX")
  cat "$tmp" >"$staged"
  rm -rf "$work"
  sync "$staged" 2>/dev/null || true
  mv -f "$staged" "$conf"
  sync "$(dirname "$conf")" 2>/dev/null || true
}

# Images kept: current ones, any a snapshot is pinned to (listed or not), the
# backup's, and a pending restore's.
gc_images() {
  local -A keep=()
  local image pin
  for image in "$STORE"/current/*; do
    [[ -L $image ]] && keep[$(basename "$(readlink "$image")")]=1
  done
  if [[ $(state_get secure_boot) == "enabled" ]]; then
    for image in "$STORE"/previous/*; do
      [[ -L $image ]] && keep[$(basename "$(readlink "$image")")]=1
    done
  fi
  for pin in "$(snapshots_dir)"/*/omarchy-boot-image; do
    [[ -f $pin ]] && keep[$(<"$pin")]=1
  done
  image=$(state_get backup_image)
  [[ -n $image ]] && keep[$image]=1
  # A pending restore's image, and the live one it replaces, which becomes
  # "Before restore".
  for image in $(kv_get "$STORE/restore/journal" IMAGE) $(kv_get "$STORE/restore/journal" PREVIOUS_IMAGE); do
    keep[$image]=1
  done

  for image in "$STORE"/images/*/; do
    image=$(basename "$image")
    [[ -n ${keep[$image]:-} ]] && continue
    rm -rf "${STORE:?}/images/$image"
    log "dropped unused boot image $image"
  done
}

# Fails when an installed kernel has no published live entry: rebooting then
# would boot an image that doesn't match the installed modules.
# The kernel the machine boots by default (omarchy-kernel set).
cmd_prefer() {
  (($# == 1)) || die "usage: prefer PKGBASE"
  [[ -L $STORE/current/$1 ]] || die "no boot image is stored for $1"
  if [[ $(state_get secure_boot) == "enabled" ]]; then
    local img
    img=$(current_image "$1")
    verify_signed_efi "$(image_dir "$img")/vmlinuz" ||
      die "cannot prefer unsigned kernel $1 ($img) while Secure Boot is enabled"
  fi
  state_set preferred "$1"
  cmd_sync
}

cmd_verify() {
  check_store
  check_esp
  local ns pkgbase kver image file status=0 vroot=/
  [[ ${OMARCHY_BOOT_TEST:-} == "1" ]] && vroot=$(live_root)
  ns=$(namespace)
  if [[ $(effective_secure_boot) == "enabled" ]]; then
    local preferred live installed_kver conf_name conf_path sw src_dir key rest token line_tokens=() kernel_opts=()
    preferred=$(preferred_kernel "$vroot")
    live=$(current_image "$preferred")
    if [[ -z $live ]]; then
      echo "No boot image for $preferred" >&2
      return 1
    fi
    src_dir=$(image_dir "$live")
    installed_kver=$(root_kernels "$vroot" | awk -v p="$preferred" '$1 == p { print $2; exit }')
    if [[ -n $installed_kver && $(image_get "$live" KVER) != "$installed_kver" ]]; then
      echo "The boot image for $preferred is $(image_get "$live" KVER), but $installed_kver is installed" >&2
      status=1
    fi
    conf_name=$(type1_conf_name "$ns" "$live" omarchy)
    conf_path=$BOOT/loader/entries/$conf_name
    for file in "$BOOT/omarchy-$ns/$live/vmlinuz" "$BOOT/omarchy-$ns/$live/initramfs.img" "$conf_path"; do
      [[ -s $file ]] || { echo "$file is missing" >&2; status=1; }
    done
    cmp -s "$src_dir/vmlinuz" "$BOOT/omarchy-$ns/$live/vmlinuz" || { echo "Published vmlinuz differs from stored image $live" >&2; status=1; }
    cmp -s "$src_dir/initramfs.img" "$BOOT/omarchy-$ns/$live/initramfs.img" || { echo "Published initramfs differs from stored image $live" >&2; status=1; }
    verify_signed_efi "$BOOT/omarchy-$ns/$live/vmlinuz" || { echo "Published vmlinuz is not signed by $CA_PEM" >&2; status=1; }
    if [[ -r $conf_path ]]; then
      grep -qx "linux   /omarchy-$ns/$live/vmlinuz" "$conf_path" || { echo "$conf_path has wrong linux path" >&2; status=1; }
      grep -qx "initrd  /omarchy-$ns/$live/initramfs.img" "$conf_path" || { echo "$conf_path has wrong initrd path" >&2; status=1; }
      while IFS=$' \t' read -r key rest || [[ -n $key ]]; do
        [[ $key == "options" ]] || continue
        IFS=$' \t' read -ra line_tokens <<<"$rest"
        for token in "${line_tokens[@]}"; do
          [[ $token == "--" ]] && break 2
          kernel_opts+=("$token")
        done
      done <"$conf_path"
      for sw in $SECURE_BOOT_SWITCHES; do
        [[ " ${kernel_opts[*]} " == *" $sw "* ]] || { echo "$conf_path options line missing $sw" >&2; status=1; }
      done
    fi
    if [[ ${OMARCHY_BOOT_DEFER_DEFAULT:-} != "1" ]]; then
      cmp -s "$SIGNED_LOADER" "$ESP/EFI/systemd/systemd-bootx64.efi" || { echo "Published systemd-bootx64.efi differs from $SIGNED_LOADER" >&2; status=1; }
      verify_signed_efi "$ESP/EFI/systemd/systemd-bootx64.efi" || { echo "Published systemd-bootx64.efi is not cleanly signed by $CA_PEM" >&2; status=1; }
      if [[ -f $ESP/EFI/BOOT/BOOTX64.EFI ]] && fallback_ours "$ESP/EFI/BOOT/BOOTX64.EFI"; then
        cmp -s "$SIGNED_LOADER" "$ESP/EFI/BOOT/BOOTX64.EFI" || { echo "Published BOOTX64.EFI differs from $SIGNED_LOADER" >&2; status=1; }
      fi
      if ! { [[ $(grep -c '^editor ' "$ESP/loader/loader.conf" 2>/dev/null || echo 0) == "1" ]] && grep -qx 'editor no' "$ESP/loader/loader.conf" 2>/dev/null; }; then
        echo "$ESP/loader/loader.conf does not cleanly set editor no" >&2
        status=1
      fi
      if ! { [[ $(grep -c '^default ' "$ESP/loader/loader.conf" 2>/dev/null || echo 0) == "1" ]] && grep -qx "default $conf_name" "$ESP/loader/loader.conf" 2>/dev/null; }; then
        echo "$ESP/loader/loader.conf does not cleanly default to $conf_name" >&2
        status=1
      fi
    fi
    return "$status"
  fi
  while read -r pkgbase kver; do
    image=$(current_image "$pkgbase")
    if [[ -z $image ]]; then
      echo "No boot image for $pkgbase $kver" >&2
      status=1
    elif [[ $(image_get "$image" KVER) != "$kver" ]]; then
      echo "The boot image for $pkgbase is $(image_get "$image" KVER), but $kver is installed" >&2
      status=1
    else
      file=$BOOT/EFI/Linux/omarchy-$ns-$image.efi
      [[ -s $file ]] || { echo "$file is missing" >&2; status=1; }
    fi
  done < <(root_kernels "$vroot")
  return "$status"
}

cmd_status() {
  check_store
  echo "backend: $(state_get backend)"
  echo "phase: $(state_get phase)"
  echo "signing: $(state_get signing)"
  echo "secure_boot: $(state_get secure_boot | grep -x enabled || echo off)"
  echo "preferred kernel: $(preferred_kernel /)"
  echo "images:"
  local image
  for image in "$STORE"/images/*/; do
    [[ -d $image ]] && echo "  $(basename "$image")  $(image_get "$(basename "$image")" KVER)"
  done
  echo "entries:"
  sed 's/^/  /' "$STORE/entries" 2>/dev/null || true
  [[ -f $STORE/restore/journal ]] && echo "restore: $(kv_get "$STORE/restore/journal" STATE) (snapshot $(kv_get "$STORE/restore/journal" SOURCE))"
  return 0
}

# --- restore ---------------------------------------------------------------------------

subvol_uuid() {
  btrfs subvolume show "$1" 2>/dev/null | sed -n 's/^[[:space:]]*UUID:[[:space:]]*//p' | sed -n 1p
}

subvol_id() {
  btrfs subvolume show "$1" 2>/dev/null | sed -n 's/^[[:space:]]*Subvolume ID:[[:space:]]*//p' | sed -n 1p
}

# The subvolumes directly inside @ (.snapshots, swap, var/lib/machines, ...),
# relative to it. A restore moves these into the new root.
root_children() {
  local root_id
  root_id=$(subvol_id "$TOP/@")
  btrfs subvolume list "$TOP" | awk -v parent="$root_id" '$7 == parent { sub(/^.* path /, ""); print }' |
    sed 's#^@/##' | sort
}

swap_holds_hibernation_image() {
  local swapfile=$TOP/@/swap/swapfile page_size
  [[ -f $swapfile ]] || return 1
  page_size=$(getconf PAGESIZE)
  [[ $(dd if="$swapfile" bs=1 skip=$((page_size - 10)) count=10 2>/dev/null | tr -d '\0') != "SWAPSPACE2" ]]
}

# Stages a restore: a writable copy of the snapshot next to @, a journal the
# initramfs applies on the next boot with nothing running, and the boot
# entries that take the machine there.
cmd_restore_stage() {
  (($# == 1)) || die "usage: restore-stage SNAPSHOT|backup"
  check_store
  mount_top
  local source=$1 source_path image kver tx staged journal=$STORE/restore/journal

  [[ $(state_get phase) == "active" ]] || die "snapshots are restored this way only once the switch to systemd-boot is finished"
  if [[ -f $journal ]] && [[ $(kv_get "$journal" STATE) =~ ^(pending|swapping|swapped)$ ]]; then
    die "a restore of snapshot $(kv_get "$journal" SOURCE) is already waiting for a reboot; cancel it first"
  fi

  if [[ $source == "backup" ]]; then
    source_path=$TOP/$(state_get backup)
    image=$(state_get backup_image)
    [[ -n $(state_get backup) && -d $source_path ]] || die "there is no previous root to go back to"
  else
    [[ $source =~ ^[0-9]+$ ]] || die "not a snapshot number: $source"
    source_path=$(snapshots_dir)/$source/snapshot
    [[ -d $source_path ]] || die "snapshot $source does not exist"
    [[ -f $(snapshots_dir)/$source/omarchy-boot-image ]] ||
      die "snapshot $source was taken before this machine switched to systemd-boot and cannot be restored"
    image=$(<"$(snapshots_dir)/$source/omarchy-boot-image")
  fi
  [[ -d $(image_dir "$image") ]] || die "the boot image of $source is gone"
  kver=$(image_get "$image" KVER)
  [[ -d $source_path/usr/lib/modules/$kver ]] || die "$source does not carry the kernel modules of its boot image ($kver)"

  swap_holds_hibernation_image && die "the swapfile holds a hibernation image; boot Omarchy normally to resume it before restoring"

  local live
  live=$(current_image "$(preferred_kernel "$(live_root)")")
  lsinitcpio "$(image_dir "$live")/initramfs.img" 2>/dev/null | grep -q 'hooks/omarchy-restore$' ||
    die "the boot image cannot apply restores yet; run omarchy-boot-rebuild first"

  if [[ $(state_get secure_boot) == "enabled" ]]; then
    local target_sync=""
    for candidate in "$source_path/usr/bin/omarchy-boot-sync" "$source_path/usr/share/omarchy/bin/omarchy-boot-sync"; do
      if [[ -r $candidate ]]; then
        target_sync=$candidate
        break
      fi
    done
    [[ -n $target_sync ]] && grep -q "effective_secure_boot" "$target_sync" ||
      die "$source predates Secure Boot support; disable Secure Boot before restoring it"
    [[ -x $source_path/usr/bin/sbverify ]] ||
      die "$source lacks sbsigntools (sbverify); disable Secure Boot before restoring it"
    verify_signed_efi "$source_path/usr/lib/systemd/boot/efi/systemd-bootx64.efi.signed" ||
      die "$source lacks a trusted signed systemd-boot loader; disable Secure Boot before restoring it"
    verify_signed_efi "$(image_dir "$image")/vmlinuz" ||
      die "$source uses an unsigned kernel ($image) and cannot be restored while Secure Boot is enabled"
    verify_signed_efi "$(image_dir "$live")/vmlinuz" ||
      die "the live boot image ($live) is unsigned and cannot stage a restore while Secure Boot is enabled"
  fi

  tx=$(date +%Y%m%d%H%M%S)
  staged=@restore-$tx
  local children child
  children=$(root_children | paste -sd: -)

  btrfs -q subvolume snapshot "$source_path" "$TOP/$staged" >/dev/null
  # Snapshots leave empty directories where nested subvolumes were; the
  # initramfs moves the real ones in and refuses anything else.
  IFS=: read -ra child_list <<<"$children"
  for child in "${child_list[@]}"; do
    if [[ -e $TOP/$staged/$child ]] && [[ -n $(ls -A "$TOP/$staged/$child" 2>/dev/null) ]]; then
      btrfs -q subvolume delete "$TOP/$staged" >/dev/null
      die "$child in $source is not empty; it cannot take the live $child subvolume"
    fi
  done

  # The swapfile subvolume moves over unchanged, so its extents (and the
  # resume offset) are today's, not the snapshot's.
  local cmdline offset
  cmdline=$(image_get "$image" CMDLINE)
  if [[ $cmdline == *resume_offset=* && -f $TOP/@/swap/swapfile ]]; then
    offset=$(btrfs inspect-internal map-swapfile -r "$TOP/@/swap/swapfile")
    # Whole parameters: an offset of 1234 is not resume_offset=12345.
    if [[ " $cmdline " != *" resume_offset=$offset "* ]]; then
      image=$(derive_image "$image" "$(sed -E "s/resume_offset=[0-9]+/resume_offset=$offset/" <<<"$cmdline")")
      sed -i -E "s/resume_offset=[0-9]+/resume_offset=$offset/" "$TOP/$staged"/etc/cmdline.d/*.conf "$TOP/$staged/etc/kernel/cmdline" 2>/dev/null || true
    fi
  fi

  mkdir -p "$STORE/restore"
  {
    echo "TX=$tx"
    echo "STATE=pending"
    echo "SOURCE=$source"
    echo "STAGED=$staged"
    echo "STAGED_UUID=$(subvol_uuid "$TOP/$staged")"
    echo "ROOT_UUID=$(subvol_uuid "$TOP/@")"
    echo "BACKUP=@backup-$tx"
    echo "CHILDREN=$children"
    echo "IMAGE=$image"
    echo "PREVIOUS_IMAGE=$live"
    # The same kernel and initramfs as the running system: the maintenance
    # boot can carry on into the restored root instead of rebooting into it.
    [[ $image == "$live" ]] && echo "SAME_IMAGE=1"
  } >"$journal.new"
  sync "$journal.new"
  mv -f "$journal.new" "$journal"
  sync "$(dirname "$journal")"

  # Hibernating now would write an image of a root that is about to move.
  mkdir -p /etc/systemd/sleep.conf.d
  printf '[Sleep]\nAllowHibernation=no\nAllowHybridSleep=no\nAllowSuspendThenHibernate=no\n' \
    >/etc/systemd/sleep.conf.d/90-omarchy-restore-pending.conf

  cmd_sync

  # Profile 0 of an image is named after the file alone, so the ids come from
  # what the sync published rather than being built here.
  local maintenance restored
  maintenance=$(entry_id omarchy-restore)
  restored=$(entry_id omarchy-restored)
  [[ -n $maintenance && -n $restored ]] || die "the restore entries were not published"
  kv_set "$journal" ONESHOT "$restored"
  bootctl set-oneshot "$maintenance" >/dev/null
  log "snapshot $source is staged; it becomes the system on the next reboot"
}

# The hibernation block restore-stage wrote: in / of the system it ran on,
# which is @ unless that was a booted snapshot, whose overlay forgets it. Run
# from a booted snapshot, the copy in @ goes too.
drop_hibernation_block() {
  rm -f /etc/systemd/sleep.conf.d/90-omarchy-restore-pending.conf "$TOP/@/etc/systemd/sleep.conf.d/90-omarchy-restore-pending.conf"
}

cmd_restore_cancel() {
  check_store
  mount_top
  local journal=$STORE/restore/journal staged
  [[ -f $journal ]] || die "no restore is waiting"
  [[ $(kv_get "$journal" STATE) == "pending" ]] || die "the restore is past the point where it can be cancelled"
  staged=$(kv_get "$journal" STAGED)
  [[ -n $staged && -d $TOP/$staged ]] && btrfs -q subvolume delete "$TOP/$staged" >/dev/null
  mv -f "$journal" "$STORE/restore/cancelled-$(kv_get "$journal" TX)"
  drop_hibernation_block
  bootctl set-oneshot "" >/dev/null 2>&1 || true
  cmd_sync
  log "restore cancelled"
}

# Runs on the first boot of the restored root: makes its image the live one,
# records the replaced root as the backup and drops the one before.
# Prints one line, "restored: ..." or "failed: ...", which the confirm
# service turns into a notice; publishing reports on stderr.
cmd_restore_commit() {
  check_store
  mount_top
  local journal=$STORE/restore/journal state tx image backup old staged
  [[ -f $journal ]] || return 0
  state=$(kv_get "$journal" STATE)
  tx=$(kv_get "$journal" TX)

  if [[ $state == "failed" ]]; then
    staged=$(kv_get "$journal" STAGED)
    [[ -d $TOP/$staged ]] && btrfs -q subvolume delete "$TOP/$staged" >/dev/null || true
    mv -f "$journal" "$STORE/restore/failed-$tx"
    drop_hibernation_block
    cmd_sync >&2
    echo "failed: $(kv_get "$STORE/restore/failed-$tx" ERROR)"
    return 0
  fi
  [[ $state == "swapped" ]] || return 0
  [[ $(subvol_uuid "$TOP/@") == "$(kv_get "$journal" STAGED_UUID)" ]] || die "@ is not the staged root; leaving the restore journal for inspection"
  # Only the restored root itself commits: booted into a snapshot instead,
  # this root's kernels would decide which of @'s boot images stay. The
  # journal waits for the next boot of @.
  if [[ $(subvol_uuid /) != "$(kv_get "$journal" STAGED_UUID)" ]]; then
    log "this boot isn't the restored root; the restore commits on its next boot" >&2
    return 0
  fi

  image=$(kv_get "$journal" IMAGE)
  backup=$(kv_get "$journal" BACKUP)
  old=$(state_get backup)

  ln -sfn "../images/$image" "$STORE/current/.$(image_get "$image" PKGBASE).new"
  mv -T "$STORE/current/.$(image_get "$image" PKGBASE).new" "$STORE/current/$(image_get "$image" PKGBASE)"
  sync "$STORE/current" 2>/dev/null || true

  # The restored root has the kernels it had then. A current image of another
  # kernel that this root lacks at that version would boot it with modules it
  # doesn't have, so it goes, and the default falls back to the restored image
  # when the preferred kernel was one of them. omarchy-boot-rebuild makes
  # images for the restored root's other kernels.
  local link pkgbase kernels
  kernels=$(root_kernels /)
  for link in "$STORE"/current/*; do
    [[ -L $link ]] || continue
    pkgbase=$(basename "$link")
    grep -qx "$pkgbase $(image_get "$(basename "$(readlink "$link")")" KVER)" <<<"$kernels" || rm -f "$link"
  done
  [[ -L $STORE/current/$(state_get preferred) ]] || state_set preferred "$(image_get "$image" PKGBASE)"

  # The restored root may have kept the restore's hibernation block (an undo
  # brings back the root it was written in).
  rm -f /etc/systemd/sleep.conf.d/90-omarchy-restore-pending.conf
  state_set backup "$backup"
  state_set backup_image "$(kv_get "$journal" PREVIOUS_IMAGE)"
  state_set backup_date "$(date '+%b %-d %H:%M')"
  rm -rf "$STORE/previous"
  local k
  for k in $(sed -n 's/^\(last_signed_[^=]*\)=.*/\1/p' "$STORE/state" 2>/dev/null); do
    state_set "$k" ""
  done

  # The restored root's entry is published before the journal says done: a
  # power loss or a failed publish leaves it swapped, and the next boot's
  # confirm commits it again. Published once more after, without the restore's
  # own entries.
  cmd_sync >&2
  kv_set "$journal" STATE done
  mv -f "$journal" "$STORE/restore/done-$tx"

  # The root before the previous restore. Never the one just replaced.
  if [[ -n $old && $old != "$backup" && -d $TOP/$old ]] && ! findmnt -n -o FSROOT | grep -qx "/$old"; then
    btrfs -q subvolume delete "$TOP/$old" >/dev/null || log "could not delete the older backup $old"
  fi
  cmd_sync >&2

  echo "restored: $(kv_get "$STORE/restore/done-$tx" SOURCE)"
}

check_secure_transition_ready() {
  check_store
  check_esp
  mount_top
  [[ $(state_get phase) == "active" ]] || die "systemd-boot phase is not active"
  local journal=$STORE/restore/journal
  if [[ -f $journal ]] && [[ $(kv_get "$journal" STATE) =~ ^(pending|swapping|swapped)$ ]]; then
    die "a snapshot restore is pending; finish or cancel it before changing Secure Boot mode"
  fi
}

cmd_secure_check() {
  check_secure_transition_ready
  local preferred live oneshot
  oneshot=$(efivar_string LoaderEntryOneShot)
  if [[ $oneshot == omarchy-"$(namespace)"-*.efi* ]]; then
    die "a one-shot UKI boot entry ($oneshot) is armed; reboot or run: sudo bootctl set-oneshot ''"
  fi
  preferred=$(preferred_kernel "$(live_root)")
  live=$(current_image "$preferred")
  [[ -n $live && -d $(image_dir "$live") ]] || die "no stored boot image for $preferred; run omarchy-boot-rebuild first"
  verify_signed_efi "$(image_dir "$live")/vmlinuz" || die "stored boot image $live is not signed by $CA_PEM"
  verify_signed_efi "$SIGNED_LOADER" || die "signed loader $SIGNED_LOADER is missing or untrusted"
}

cmd_secure_enable() {
  cmd_secure_check
  # Stage and verify Type 1 files without touching loader.conf, the live ESP
  # loader, existing UKIs, or state; then commit all of them together.
  OMARCHY_BOOT_DEFER_DEFAULT=1 MODE_OVERRIDE=enabled cmd_sync
  OMARCHY_BOOT_DEFER_DEFAULT=1 MODE_OVERRIDE=enabled cmd_verify
  rm -f "$STORE/pending-default"
  sync_signed_loader
  state_set secure_boot enabled
  cmd_sync
  cmd_verify
}

cmd_secure_disable() {
  check_secure_transition_ready
  local ns oneshot keep_dir="" file
  ns=$(namespace)
  oneshot=$(efivar_string LoaderEntryOneShot)
  # Stage and verify UKI entries FIRST while loader.conf, Type 1 files, and previous links stay intact.
  OMARCHY_BOOT_DEFER_DEFAULT=1 MODE_OVERRIDE=off cmd_sync
  OMARCHY_BOOT_DEFER_DEFAULT=1 MODE_OVERRIDE=off cmd_verify
  rm -f "$STORE/pending-default"

  state_set secure_boot off
  cmd_sync
  cmd_verify
  rm -rf "$STORE/previous"
  if [[ $oneshot == omarchy-"$ns"-*.conf ]]; then
    keep_dir=$(type1_conf_image_dir "$ns" "$BOOT/loader/entries/$oneshot")
  fi
  for file in "$BOOT"/loader/entries/omarchy-"$ns"-*.conf "$BOOT"/loader/entries/omarchy-"$ns"-*.conf.*; do
    [[ -e $file ]] || continue
    [[ -n $oneshot && $(basename "$file") == "$oneshot" ]] && continue
    rm -f "$file"
    log "removed $(basename "$file")"
  done
  for file in "$BOOT"/omarchy-"$ns"/*; do
    [[ -e $file ]] || continue
    [[ -n $keep_dir && $(basename "$file") == "$keep_dir" ]] && continue
    rm -rf "$file"
    log "removed Type 1 directory $(basename "$file")"
  done
  rmdir "$BOOT/omarchy-$ns" 2>/dev/null || true
  gc_images
}

case ${1:-} in
sync) with_lock; cmd_sync ;;
import) shift; with_lock; check_store; cmd_import "$@" ;;
pin) shift; with_lock; check_store; mount_top; cmd_pin "$@" ;;
cmdline) assemble_cmdline "${OMARCHY_BOOT_CMDLINE_ROOT:-/}" ; echo ;;
prefer) shift; with_lock; check_store; cmd_prefer "$@" ;;
windows) with_lock; cmd_windows ;;
preferred) preferred_kernel "$([[ ${OMARCHY_BOOT_TEST:-} == "1" ]] && live_root || echo /)" ;;
secure-check) with_lock; cmd_secure_check ;;
secure-enable) with_lock; cmd_secure_enable ;;
secure-disable) with_lock; cmd_secure_disable ;;
verify) cmd_verify ;;
status) cmd_status ;;
restore-stage) shift; with_lock; cmd_restore_stage "$@" ;;
restore-cancel) with_lock; cmd_restore_cancel ;;
restore-commit) with_lock; cmd_restore_commit ;;
*) die "usage: omarchy-boot-sync sync | import PKGBASE KVER VMLINUZ INITRAMFS | pin NUMBER | windows | verify | status | restore-stage SNAPSHOT|backup | restore-cancel | restore-commit" ;;
esac
