#!/bin/bash

# omarchy:summary=First-boot provisioning: create the user on a machine installed in deferred provisioning
# omarchy:requires-sudo=true
# omarchy:hidden=true

# Runs on tty1 via omarchy-provision-owner.service when /var/lib/omarchy/provisioning/pending
# exists — the state a deferred-provisioning ISO install or omarchy-system-factory-reset leaves
# behind. Asks what the installer asks, in its order and on its screens (the
# language, the keyboard, then the account), then for the OEM's agreement where
# the install laid one down (install/provisioning/oem.sh), creates the user
# with the groups system setup recorded, finalizes it offline, re-keys LUKS from
# the throwaway install passphrase to the user's password, and hands off to the
# login screen.
# A platform whose boot package owns its boot chain prepares it, drops the
# install key's unlock from it and records the kept key slot through
# omarchy-lifecycle-dispatch.

set -euo pipefail

PROVISIONING_DIR=/var/lib/omarchy/provisioning
# Exported, as a systemd service has none to inherit and the install scripts
# it runs need it.
export OMARCHY_PATH="${OMARCHY_PATH:-/usr/share/omarchy}"
LOG_FILE=/var/log/omarchy-provision-owner.log

if (( EUID != 0 )); then
  echo "Error: omarchy-provision-owner must run as root" >&2
  exit 1
fi

[[ -f $PROVISIONING_DIR/pending ]] || exit 0

# Never set up a user on a half-wiped system: while a factory wipe is still
# pending (i.e. it failed this boot), stand down and let it retry next boot.
if [[ -f $PROVISIONING_DIR/wipe-pending ]]; then
  echo "omarchy-provision-owner: factory wipe still pending; not running user setup" >&2
  exit 1
fi

export PATH="$OMARCHY_PATH/bin:$PATH"

REKEY_STATE=$PROVISIONING_DIR/luks-rekey.state
source "$OMARCHY_PATH/install/provisioning/luks-rekey.sh"

# The shared setup form — the same questions, prompts, and validation the ISO
# configurator's user step asks. The ISO vendors this very file out of the
# runtime package it bundles, so an install and the first boot that finishes it
# can never offer different layouts or accept different usernames.
source "$OMARCHY_PATH/install/provisioning/setup-form.sh"

# The installer's console font, from the same file the ISO vendors.
source "$OMARCHY_PATH/install/provisioning/console-font.sh"

# Setup is drawn in kmscon, as the installer is. kmscon takes its keyboard
# layout and font once, at its start: when the keyboard step changes either,
# the attempt saves its answers to KMSCON_RESUME and exits KMSCON_RELAUNCH, and
# main starts kmscon again to carry on from the account step.
source "$OMARCHY_PATH/install/provisioning/kmscon.sh"
KMSCON_STATE=/run/omarchy-provision-owner
KMSCON_RESUME=$KMSCON_STATE/resume
KMSCON_RELAUNCH=75
# Where the finished icon was drawn, for setup to paint it again as kmscon
# goes (show_finished_icon), and there once kmscon has, for the painter not to
# wait for it any longer.
FINISHED_ICON=$KMSCON_STATE/finished-icon
FINISHED_ICON_GO=$KMSCON_STATE/finished-icon-go
# kmscon's fonts draw what the console's cannot.
[[ ${OMARCHY_KMSCON:-} != 1 ]] || OMARCHY_FORM_CONSOLE_LANGUAGES+=" ja ko zh-CN zh-TW"

# What the OEM that prepared this machine left for its owner, if one did.
source "$OMARCHY_PATH/install/provisioning/oem.sh"
omarchy_oem_load

# Unlike a fresh install target, this machine already has accounts; a pinned
# resume (below) bypasses the prompt entirely.
omarchy_username_taken() { getent passwd "$1" >/dev/null; }

# Every screen is laid out in a column the width of the Omarchy logo, which
# heads the steps of the form.
LOGO_PATH="$OMARCHY_PATH/logo.txt"
LOGO_WIDTH=$(awk '{ if (length > max) max = length } END { print max+0 }' "$LOGO_PATH" 2>/dev/null || echo 0)
LOGO_HEIGHT=$(wc -l <"$LOGO_PATH" 2>/dev/null || echo 0)
(( LOGO_WIDTH > 0 )) || LOGO_WIDTH=81
(( LOGO_HEIGHT > 0 )) || LOGO_HEIGHT=1
LOGO_COLOR=2

# The screens setup opens and ends on, the greeter and the agreement, carry
# the brand: an OEM's logo where it left one, in its colour where it named one
# (the palette's bright red, which setup draws nothing else in), else Omarchy's.
brand_logo() {
  BRAND_LOGO_PATH=$1
  BRAND_LOGO_WIDTH=$(awk '{ if (length > max) max = length } END { print max+0 }' "$1" 2>/dev/null || echo 0)
  BRAND_LOGO_HEIGHT=$(wc -l <"$1" 2>/dev/null || echo 0)
  (( BRAND_LOGO_HEIGHT > 0 )) || BRAND_LOGO_HEIGHT=1
}
brand_logo "${OMARCHY_OEM_LOGO:-$LOGO_PATH}"
BRAND_LOGO_COLOR=2
BRAND_SHIMMER=(2 10 6 10)
if [[ -n $OMARCHY_OEM_COLOR ]]; then
  BRAND_LOGO_COLOR=9
  BRAND_SHIMMER=(9 9 15 9)
fi

# The language setup is in: what an attempt picked, for the retry that follows a
# failed one, and the preset the installed system reads its language from.
LANGUAGE_FILE=/run/omarchy-provision-owner.language
LANGUAGE_MARKER=/etc/omarchy/language

# The installer's font at the installer's size (console-font.sh), so first boot
# reads as the screen the install left. A system without Terminus keeps the
# font the kernel booted in, which is that size too but draws English only.
fit_console_font() {
  local tty
  tty=$(tty 2>/dev/null) || tty=""
  [[ $tty == /dev/tty[0-9]* ]] || return 0
  omarchy_console_font "$tty" || OMARCHY_FORM_CONSOLE_LANGUAGES=en
}

# An OEM's logo may be drawn in braille dots, which the console font has none
# of: for as long as a branded screen is up the font draws the ones this logo
# uses, in place of characters that neither the logo nor that screen's text
# does. fit_console_font puts the form's font back. A console that cannot be
# given them shows Omarchy's logo instead.
brand_console_font() {
  local tty
  # U+2800 to U+28FF, by their bytes: a range of the characters needs a locale that collates them.
  [[ $BRAND_LOGO_PATH != "$LOGO_PATH" ]] && LC_ALL=C grep -q $'\xe2[\xa0-\xa3]' "$BRAND_LOGO_PATH" || return 0
  tty=$(tty 2>/dev/null) || tty=""
  [[ $tty == /dev/tty[0-9]* ]] || return 0

  omarchy_console_font "$tty" "$BRAND_LOGO_PATH" "${OMARCHY_OEM_DIR:-/etc/omarchy/oem}/oem.json" ${OMARCHY_OEM_EULA:+"$OMARCHY_OEM_EULA"} \
    "$OMARCHY_PATH/default/i18n/en/cli.json" "$OMARCHY_PATH/default/i18n/${OMARCHY_FORM_LANGUAGE:-en}/cli.json" || brand_logo "$LOGO_PATH"
}

# Same Tokyo Night VT palette the ISO configurator sets, so the first-boot
# form looks like a continuation of the install.
set_tokyo_night_colors() {
  [[ $(tty 2>/dev/null) == /dev/tty* ]] || return 0
  echo -en "\e]P01a1b26"; echo -en "\e]P1f7768e"; echo -en "\e]P29ece6a"
  echo -en "\e]P3e0af68"; echo -en "\e]P47aa2f7"; echo -en "\e]P5bb9af7"
  echo -en "\e]P67dcfff"; echo -en "\e]P7a9b1d6"; echo -en "\e]P8414868"
  echo -en "\e]P9f7768e"; echo -en "\e]PA9ece6a"; echo -en "\e]PBe0af68"
  echo -en "\e]PC7aa2f7"; echo -en "\e]PDbb9af7"; echo -en "\e]PE7dcfff"
  echo -en "\e]PFc0caf5"
  [[ -z $OMARCHY_OEM_COLOR ]] || echo -en "\e]P9${OMARCHY_OEM_COLOR#\#}"
  echo -en "\033[0m"
  clear
}

# Setup opens in the language an earlier attempt picked, else the one the
# install media preset, else English.
initial_language() {
  local code=""
  [[ -r $LANGUAGE_FILE ]] && { read -r code <"$LANGUAGE_FILE" || true; }
  [[ -n $code || ! -r $LANGUAGE_MARKER ]] || read -r code <"$LANGUAGE_MARKER" || true
  jq -e --arg code "$code" 'has($code)' "$OMARCHY_PATH/default/i18n/locales.json" >/dev/null 2>&1 || code=en
  omarchy_form_use_language "$code"
}

measure_terminal() {
  TERM_WIDTH=$(stty size 2>/dev/null </dev/tty | awk '{print $2}')
  (( TERM_WIDTH > 0 )) || TERM_WIDTH=${COLUMNS:-80}

  PADDING_LEFT=$(((TERM_WIDTH - LOGO_WIDTH) / 2))
  (( PADDING_LEFT < 0 )) && PADDING_LEFT=0
  PADDING_LEFT_SPACES=$(printf "%*s" "$PADDING_LEFT" "")

  local padding="0 0 0 $PADDING_LEFT"
  export GUM_CHOOSE_PADDING="$padding"
  export GUM_FILTER_PADDING="$padding"
  export GUM_INPUT_PADDING="$padding"
  export GUM_SPIN_PADDING="$padding"
  export GUM_TABLE_PADDING="$padding"
  export GUM_CONFIRM_PADDING="$padding"
}

clear_logo() {
  measure_terminal
  printf "\033[H\033[2J"
  # An OEM's logo is art, which may open with dashes.
  gum style --foreground "$LOGO_COLOR" --padding "1 0 0 $PADDING_LEFT" -- "$(<"$LOGO_PATH")"
}

step() {
  clear_logo
  echo
  gum style --padding "0 0 0 $PADDING_LEFT" "$1"
  echo
}

say() {
  gum style --padding "0 0 0 $PADDING_LEFT" "$@"
}

notice() {
  clear_logo
  echo
  printf '%*s\033[32m● \033[0m%s\n' "$PADDING_LEFT" '' "$1"
  sleep "${2:-2}"
  echo
}

log_step() {
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] oem-setup: $1" >>"$LOG_FILE"
}

# ── Setup progress screen ────────────────────────────────────────────────────
#
# The ISO install dashboard's own screen, drawn by the file it vendors from this
# package, so first-boot account setup continues the install on the screen it
# started on: the same traced icon, percentage and rotating tips. Position =
# max(floor, work) in per-mille, monotonic; the floor is asymptotic per phase
# band and the work signal counts finalize-user's run_logged scripts in the log.
source "$OMARCHY_PATH/install/provisioning/progress-icon.sh"

CSI=$'\033['
RESET="${CSI}0m"
DIM="${CSI}2m"
HIDE_CURSOR="${CSI}?25l"
SHOW_CURSOR="${CSI}?25h"
CLEAR="${CSI}2J${CSI}H"
BRAND_LOGO_SGR="${CSI}$((BRAND_LOGO_COLOR < 8 ? 30 + BRAND_LOGO_COLOR : 82 + BRAND_LOGO_COLOR))m"

STATE_FILE=/run/omarchy-provision-owner.state
FINALIZE_WARNING_FLAG=/run/omarchy-provision-owner.finalize-warning

# Read once the language is known; each key is spelled out so the catalog
# check can see it is used.
load_tips() {
  tips=(
    "$(omarchy_form_text ownerSetup.tip.menu)"
    "$(omarchy_form_text ownerSetup.tip.keybindings)"
    "$(omarchy_form_text ownerSetup.tip.superKey)"
    "$(omarchy_form_text ownerSetup.tip.signPdfs)"
    "$(omarchy_form_text ownerSetup.tip.localSend)"
    "$(omarchy_form_text ownerSetup.tip.webApps)"
    "$(omarchy_form_text ownerSetup.tip.terminal)"
    "$(omarchy_form_text ownerSetup.tip.media)"
    "$(omarchy_form_text ownerSetup.tip.ocr)"
    "$(omarchy_form_text ownerSetup.tip.screenshots)"
    "$(omarchy_form_text ownerSetup.tip.reminders)"
    "$(omarchy_form_text ownerSetup.tip.themes)"
    "$(omarchy_form_text ownerSetup.tip.transparentBar)"
    "$(omarchy_form_text ownerSetup.tip.windows)"
    "$(omarchy_form_text ownerSetup.tip.clipboard)"
    "$(omarchy_form_text ownerSetup.tip.workspaces)"
    "$(omarchy_form_text ownerSetup.tip.colorPicker)"
    "$(omarchy_form_text ownerSetup.tip.update)"
  )
  SETUP_TIP_LINE=$(omarchy_form_text ownerSetup.tipLine)
}

term_cols() {
  local cols
  cols=$(stty size 2>/dev/null </dev/tty | awk '{print $2}')
  [[ $cols =~ ^[0-9]+$ ]] && (( cols > 0 )) || cols=${COLUMNS:-80}
  printf '%s' "$cols"
}

# A fingerprint of the console geometry: the VT size plus the framebuffer's
# identity and pixel size. On a fresh first boot the VT can come up in a
# transitional ~80x25 mode and only widen to the real resolution a second or
# more later, when virtio-gpu's KMS takes over (or the SDL window's size lands).
# Watching this signature settle — rather than trusting one early reading — is
# what keeps the greeter from measuring that transient and rendering into it.
console_signature() {
  local size fb_size="" fb_name=""
  size=$(stty size 2>/dev/null </dev/tty) || return 1
  [[ $size =~ ^[0-9]+\ [0-9]+$ ]] || return 1
  [[ -r /sys/class/graphics/fb0/virtual_size ]] && fb_size=$(<"/sys/class/graphics/fb0/virtual_size")
  [[ -r /sys/class/graphics/fb0/name ]] && fb_name=$(<"/sys/class/graphics/fb0/name")
  printf '%s|%s|%s' "$size" "$fb_name" "$fb_size"
}

# Block until the console signature holds unchanged for a genuine quiet stretch
# (quiet_samples * 100ms), giving up after max_samples * 100ms. Returns 0 once
# quiet, 1 on timeout.
wait_console_stable() {
  local max_samples="${1:-100}" quiet_samples="${2:-15}"
  local previous="" current="" quiet=0 i
  for ((i = 0; i < max_samples; i++)); do
    current=$(console_signature 2>/dev/null || true)
    if [[ -n $current && $current == "$previous" ]]; then
      quiet=$((quiet + 1))
      (( quiet >= quiet_samples )) && return 0
    else
      previous=$current
      quiet=0
    fi
    sleep 0.1
  done
  return 1
}

left_padding() {
  local width="${1:-$LOGO_WIDTH}" cols pad
  cols=$(term_cols)
  pad=$(((cols - width) / 2))
  (( pad < 0 )) && pad=0
  printf '%*s' "$pad" ''
}

# Monotonic clock so an NTP step during setup cannot jump the progress.
set_now() {
  local up rest
  if read -r up rest </proc/uptime 2>/dev/null && [[ $up == [0-9]* ]]; then
    NOW=${up%%.*}
  else
    NOW=$EPOCHSECONDS
  fi
  return 0
}

# One tip per 8 seconds, elapsed-time driven like the install dashboard. It
# sets SETUP_TIP rather than printing it, so a frame forks no subshell for it.
current_tip() {
  SETUP_TIP=${SETUP_TIP_LINE//%1/${tips[(NOW - SETUP_T0) / 8 % ${#tips[@]}]}}
}

SETUP_POS=10
SETUP_PHASE=""
SETUP_PHASE_T0=0
SETUP_T0=0
NOW=0
FINALIZE_BASE=-1
FINALIZE_TOTAL=$(grep -c '^run_logged' "$OMARCHY_PATH/install/user/all.sh" 2>/dev/null || echo 0)

# Whether this boot will re-key LUKS (encrypted installs stage a throwaway key).
# The re-key rebuilds the UKI and is the slowest single step, so it needs a wide
# band of its own; unencrypted installs skip it and let finalize take the room.
REKEY_PENDING=false
[[ -f $PROVISIONING_DIR/luks-key ]] && REKEY_PENDING=true

# Per-mille bands per phase: "lo hi tau". tau shapes the asymptotic time floor;
# it is not a duration prediction. A wide band moves visibly; a narrow one looks
# stuck. Skipped phases leave a gap the next band's floor crosses on its own.
phase_band() {
  if $REKEY_PENDING; then
    # Encrypted: finalize is quick, the LUKS re-key (UKI rebuild) is the long
    # pole — give it nearly half the drawing so it keeps moving while it works.
    case $1 in
      finalize) echo "80 480 40" ;;
      rekey)    echo "480 950 30" ;;
      boot)     echo "950 990 20" ;;
      done)     echo "1000 1000 1" ;;
      *)        echo "10 80 3" ;;
    esac
  else
    # Unencrypted: finalize is the dominant step.
    case $1 in
      finalize) echo "80 900 45" ;;
      boot)     echo "900 990 20" ;;
      done)     echo "1000 1000 1" ;;
      *)        echo "10 80 3" ;;
    esac
  fi
}

setup_progress() {
  local phase lo hi tau t span floor work completed
  phase=$(cat "$STATE_FILE" 2>/dev/null || true)
  [[ -n $phase ]] || phase=account

  if [[ $phase != "$SETUP_PHASE" ]]; then
    SETUP_PHASE=$phase
    SETUP_PHASE_T0=$NOW
    FINALIZE_BASE=-1
  fi

  read -r lo hi tau <<<"$(phase_band "$phase")"
  (( lo < SETUP_POS )) && lo=$SETUP_POS

  t=$((NOW - SETUP_PHASE_T0))
  span=$((hi - lo))
  floor=$lo
  (( span > 1 )) && floor=$((lo + (span - 1) * t / (t + tau)))

  work=0
  if [[ $phase == "finalize" ]] && (( FINALIZE_TOTAL > 0 )); then
    completed=$(grep -cE '] (Completed|Failed): ' "$LOG_FILE" 2>/dev/null || true)
    [[ $completed =~ ^[0-9]+$ ]] || completed=0
    (( FINALIZE_BASE < 0 )) && FINALIZE_BASE=$completed
    completed=$((completed - FINALIZE_BASE))
    (( completed < 0 )) && completed=0
    (( completed > FINALIZE_TOTAL )) && completed=$FINALIZE_TOTAL
    work=$((lo + (hi - lo) * completed / FINALIZE_TOTAL))
  fi

  (( floor > SETUP_POS )) && SETUP_POS=$floor
  (( work > SETUP_POS )) && SETUP_POS=$work
  (( SETUP_POS > 1000 )) && SETUP_POS=1000
  return 0
}

render_setup_static() {
  printf '%s' "$HIDE_CURSOR"
  progress_icon_layout /dev/tty "$LOGO_WIDTH"
  progress_icon_static
}

# The VT can still resize under us (the same virtio-gpu KMS handoff the greeter
# watches for); progress_icon_frame redraws at the new size when it does. Only
# the worker's successful exit completes the drawing (render_setup_finish).
render_setup_dynamic() {
  local poll="${1:-1}" pm
  set_now
  (( poll )) && setup_progress
  pm=$SETUP_POS
  (( pm > 999 )) && pm=999
  current_tip
  progress_icon_frame "$pm" "" "$SETUP_TIP"
}

render_setup_finish() {
  current_tip
  progress_icon_finish "" "$SETUP_TIP"
}

# The first thing a new owner sees, shown once before the keyboard step:
# the logo (vertically centered like the boot logo) running a looping ColorShift,
# the Omarchy tagline, and a hint. Return skips ahead into setup at any time.
greeter_screen() {
  local anim="" drawn_sig cur_sig resized=0

  # Paint the whole splash for the console's *current* geometry. Kept in a
  # nested function so the wait loop below can repaint it verbatim if the VT
  # resizes out from under us: a late resize (virtio-gpu KMS handoff, or the SDL
  # window's size arriving) scrolls the old frame into the top-left and resets
  # the DEC saved cursor ttfx paints from — exactly the tiled/garbled logo we saw
  # on a fresh first boot. Redrawing on every resize beats any fixed-length
  # startup wait, which can only ever guess when the console has stopped moving.
  _greeter_draw() {
    local rows cols top content_h logo_row tagline_row hint_row
    local tagline hint tpad hpad pad line i

    cols=$(term_cols)
    rows=$(stty size 2>/dev/null </dev/tty | awk '{print $1}')
    [[ $rows =~ ^[0-9]+$ ]] || rows=${LINES:-24}

    tagline=${OMARCHY_OEM_TAGLINE:-"Beautiful, Fun & Agentic Linux by DHH"}
    hint="Press Return to Start Setup"

    printf '%s%s' "$HIDE_CURSOR" "$CLEAR"

    # Console still too narrow for the logo (a transient small mode): skip the
    # logo and animation rather than wrap them into mush — just center the
    # words. The redraw loop repaints the full splash once the VT widens.
    if (( cols <= BRAND_LOGO_WIDTH )); then
      local mid=$(( rows / 2 ))
      tpad=$(( (cols - ${#tagline}) / 2 )); (( tpad < 0 )) && tpad=0
      hpad=$(( (cols - ${#hint}) / 2 )); (( hpad < 0 )) && hpad=0
      printf '%s%d;%dH%s' "$CSI" "$mid" "$((tpad + 1))" "$tagline"
      printf '%s%d;%dH%s%s%s' "$CSI" "$((mid + 2))" "$((hpad + 1))" "$DIM" "$hint" "$RESET"
      return 0
    fi

    # logo + blank + tagline + blank + hint
    content_h=$(( BRAND_LOGO_HEIGHT + 4 ))
    top=$(( (rows - content_h) / 2 )); (( top < 0 )) && top=0
    logo_row=$(( top + 1 ))
    tagline_row=$(( top + BRAND_LOGO_HEIGHT + 2 ))
    hint_row=$(( top + BRAND_LOGO_HEIGHT + 4 ))

    # Draw each logo row at an explicit column so nothing can wrap it even if a
    # measurement is off by one; left_padding centers it for the current width.
    pad="$(left_padding "$BRAND_LOGO_WIDTH")"
    i=0
    while IFS= read -r line; do
      printf '%s%d;1H%s%b%s%b' "$CSI" "$((logo_row + i))" "$pad" "$BRAND_LOGO_SGR" "$line" "$RESET"
      i=$((i + 1))
    done <"$BRAND_LOGO_PATH"

    tpad=$(( (cols - ${#tagline}) / 2 )); (( tpad < 0 )) && tpad=0
    printf '%s%d;%dH%s' "$CSI" "$tagline_row" "$((tpad + 1))" "$tagline"

    hpad=$(( (cols - ${#hint}) / 2 )); (( hpad < 0 )) && hpad=0
    printf '%s%d;%dH%s%s%s' "$CSI" "$hint_row" "$((hpad + 1))" "$DIM" "$hint" "$RESET"

    # ColorShift the logo: a green base (indexed color 2) with a cyan accent (6)
    # drifting through, settling on green. Indexed ANSI colors, not hex — the
    # framebuffer console can't render ttfx's truecolor faithfully (it crushes the
    # palette to a muddy lavender), but the 16 indexed colors map to the Tokyo
    # Night palette and render true. One long-running invocation (many cycles) so
    # it never restarts — a restart is what flashed. The effect reads from
    # /dev/null so it never swallows the Return the foreground read waits on;
    # --reuse-canvas paints upward from the saved cursor, anchored one row below
    # the logo to repaint exactly the rows drawn above.
    #
    # --xterm-colors is what actually keeps the palette indexed: ttfx resolves
    # even indexed stops to truecolor otherwise, and the console reduces 256-colour
    # codes well but 24-bit ones badly — that reduction is the muddy lavender.
    # It also pins the settle colour to index 2, matching the green logo drawn
    # above. --canvas-width is cols-2, not cols-1: ttfx centres its text two
    # columns right of plain centering, so cols-1 lands the animated logo a
    # column off the static one and it jumps when the effect starts.
    #
    # kmscon draws 256-colour codes as xterm's own colours, not the palette's,
    # and draws 24-bit ones as given: there the stops are the palette's colours.
    local stops=("${BRAND_SHIMMER[@]}" "$BRAND_LOGO_COLOR") indexed=(--xterm-colors) i
    if [[ ${OMARCHY_KMSCON:-} == 1 ]]; then
      indexed=()
      for i in "${!stops[@]}"; do
        case ${stops[i]} in
          6) stops[i]=7dcfff ;;
          9) stops[i]=${OMARCHY_OEM_COLOR#\#} ;;
          15) stops[i]=c0caf5 ;;
          *) stops[i]=9ece6a ;;
        esac
      done
    fi
    printf '%s%d;1H\0337' "$CSI" "$((logo_row + BRAND_LOGO_HEIGHT))"
    # Run ttfx directly (not inside a `while` subshell) so $anim is ttfx's own
    # PID: killing a wrapping subshell would orphan ttfx, which then keeps
    # painting the logo over the keyboard step. --cycles is high enough that it
    # never ends on its own before Return.
    ttfx -i "$BRAND_LOGO_PATH" \
      --canvas-width "$((cols > 2 ? cols - 2 : cols))" \
      --anchor-text c \
      --frame-rate 60 \
      --reuse-canvas \
      "${indexed[@]}" \
      colorshift \
      --gradient-stops "${stops[@]:0:${#BRAND_SHIMMER[@]}}" \
      --gradient-frames 3 \
      --cycles 1000 \
      --final-gradient-stops "${stops[-1]}" \
      </dev/null >/dev/tty 2>/dev/null &
    anim=$!
  }

  _greeter_kill_anim() {
    [[ -n ${anim:-} ]] || return 0
    # Guard both: `kill` returns non-zero if ttfx already exited (crash, or a
    # resize race), and `wait` reports ttfx's kill signal (143) — either would
    # abort provisioning under `set -e` and drop straight to the login screen.
    kill "$anim" 2>/dev/null || true
    wait "$anim" 2>/dev/null || true
    anim=""
  }

  # Let the console settle before the first paint, then size the font to it.
  wait_console_stable 100 15 || true
  fit_console_font
  brand_console_font
  wait_console_stable 30 5 || true

  trap 'resized=1' WINCH

  _greeter_draw
  drawn_sig=$(console_signature 2>/dev/null || true)

  # Wait for Return, but keep watching the geometry. On any resize (SIGWINCH or
  # a changed signature) tear the animation down, settle, re-fit the font, and
  # repaint — so a resize arriving five seconds in looks the same as one that
  # never happened.
  while true; do
    if IFS= read -r -t 0.2 _ </dev/tty; then
      break
    fi
    cur_sig=$(console_signature 2>/dev/null || true)
    if (( resized )) || [[ -n $cur_sig && $cur_sig != "$drawn_sig" ]]; then
      _greeter_kill_anim
      stty sane </dev/tty 2>/dev/null || true
      # Cleared before the font changes under it: what is on screen is drawn
      # from whichever font is set, and the brand's dots are in only one.
      printf '%s' "$CLEAR"
      wait_console_stable 50 5 || true
      fit_console_font
      brand_console_font
      wait_console_stable 30 5 || true
      _greeter_draw
      drawn_sig=$(console_signature 2>/dev/null || true)
      # Clear last so the font-fitting's own SIGWINCHes don't re-trigger a redraw.
      resized=0
    fi
  done

  trap - WINCH
  _greeter_kill_anim
  # ttfx leaves the tty in raw/no-echo mode when killed; restore it or the gum
  # prompts in the keyboard step that follows silently die. Then clear the
  # leftover animation frame.
  stty sane </dev/tty 2>/dev/null || true
  printf '%s%s%s' "$RESET" "$CLEAR" "$SHOW_CURSOR"
  # The form's font again, for whatever comes next, a failure to start included.
  fit_console_font
}

# The first screen, as in the installer: every Omarchy language, and the rest of
# setup in the one picked where the console can draw it. Esc has nothing to go
# back to, so it asks again. Ctrl+C is the way out of a screen the owner cannot
# get past: see confirm_reboot.
language_form() {
  local status

  while true; do
    clear_logo
    echo
    say "$(omarchy_form_text setupForm.machineIntro)"
    echo
    omarchy_prompt_language && status=0 || status=$?
    ((status == 0)) && break
    ((status == OMARCHY_FORM_SIGNAL)) && confirm_reboot && exec systemctl reboot
  done

  printf '%s\n' "$language" >"$LANGUAGE_FILE"
}

# The keyboard step the ISO configurator runs — deferred to first boot for OEM
# installs, so the machine's owner picks their own layout. Applied immediately
# (live VT + persisted) so the password typed next, and the LUKS re-key below,
# use the chosen layout. A layout that did not take is asked for again: the
# password form must never be typed in a layout the disk unlock won't use.
# Three failures in a row mean the machine can't set a layout at all (a
# missing or broken localectl, say), so the attempt fails and setup's own
# retry-or-console screen takes over instead of asking forever.
keyboard_form() {
  local status failures=0

  while true; do
    # Every step sits under the one heading, so the screen does not shift
    # from one to the next.
    step "$(omarchy_form_text setupForm.machineIntro)"
    if ! omarchy_form_language_drawn "$language"; then
      # English on purpose: the console cannot draw this language to say it in.
      say --foreground 8 "Setup stays in English. Omarchy will be in $(omarchy_form_language_label "$language") once set up."
      echo
    fi

    omarchy_prompt_keyboard && status=0 || status=$?
    if ((status == 0)); then
      apply_keyboard "$keyboard" && break
      if ((++failures >= 3)); then
        log_step "no keyboard layout could be set after $failures attempts"
        notice "$(omarchy_form_text ownerSetup.keyboardFailed)" 4
        return 1
      fi
      notice "$(omarchy_form_text ownerSetup.keyboardRetry "${keyboard_label:-$keyboard}")" 4
      continue
    fi

    # Esc means "back", to the language picker.
    if ((status == OMARCHY_FORM_BACK)); then
      language_form
      continue
    fi

    # Rebooting is safe but not an escape from setup: this service runs again
    # at next boot, and encrypted machines still auto-unlock from the staged
    # keyfile until the re-key below. Confirm it so a stray Ctrl+C doesn't
    # bounce the machine.
    confirm_reboot && exec systemctl reboot
  done

  omarchy_persist_input_selection

  # The password ahead is typed under the layout just picked, and the language
  # reads in its own Han forms: both need kmscon started again.
  if [[ ${OMARCHY_KMSCON:-} == 1 ]] &&
    [[ $(omarchy_keymap_xkb "$keyboard") != "$OMARCHY_KMSCON_XKB" || $(omarchy_kmscon_face "$language") != "$OMARCHY_KMSCON_FACE" ]]; then
    (
      umask 077
      declare -p language keyboard keyboard_label keyboard_input_method keyboard_xkb_layout 2>/dev/null >"$KMSCON_RESUME"
    )
    exit $KMSCON_RELAUNCH
  fi
}

confirm_reboot() {
  clear_logo
  echo
  say "$(omarchy_form_text ownerSetup.rebootNote)"
  echo
  gum confirm --affirmative "$(omarchy_form_text ownerSetup.rebootYes)" --negative "$(omarchy_form_text ownerSetup.rebootNo)" \
    "$(omarchy_form_text ownerSetup.rebootPrompt)"
}

# Declining the agreement offers to shut down, and going back to it is the
# answer in focus.
confirm_shutdown() {
  clear_logo
  echo
  say --width "$((PADDING_LEFT + LOGO_WIDTH))" "$(omarchy_form_text ownerSetup.eulaDeclined)"
  echo
  gum confirm --default=false --affirmative "$(omarchy_form_text ownerSetup.eulaShutDownYes)" \
    --negative "$(omarchy_form_text ownerSetup.eulaShutDownNo)" "$(omarchy_form_text ownerSetup.eulaShutDownPrompt)"
}

# The OEM's agreement, where it left one: setup's last question, asked before
# anything is created, so a machine whose owner declines is still as it left
# the factory.
EULA_ACCEPTED_AT=""

eula_form() {
  local status
  [[ -n $OMARCHY_OEM_EULA ]] || return 0

  # Setup ends as it opened, under the brand.
  printf '\033[H\033[2J'
  brand_console_font
  local LOGO_PATH=$BRAND_LOGO_PATH LOGO_HEIGHT=$BRAND_LOGO_HEIGHT LOGO_COLOR=$BRAND_LOGO_COLOR

  # The agreement reads its own keys, so there Ctrl+C is a signal, and one
  # that lands while the screen after it is drawn must not end setup.
  trap : INT
  while true; do
    omarchy_oem_eula && status=0 || status=$?
    if ((status == 0)); then
      EULA_ACCEPTED_AT=$(date -u +%Y-%m-%dT%H:%M:%SZ)
      break
    elif ((status == OMARCHY_FORM_BACK)); then
      break
    elif ((status == OMARCHY_FORM_SIGNAL)); then
      confirm_reboot && exec systemctl reboot
    else
      confirm_shutdown && exec systemctl poweroff
    fi
  done
  trap - INT
  printf '\033[H\033[2J'
  fit_console_font
  return "$status"
}

# Whose agreement was accepted, by whom and when, for the OEM and the owner to
# refer to. The hash is of the text as the ISO laid it down.
record_eula() {
  [[ -n $EULA_ACCEPTED_AT ]] || return 0
  mkdir -p /var/lib/omarchy/oem
  jq -n --arg oem "$OMARCHY_OEM_NAME" --arg user "$username" --arg at "$EULA_ACCEPTED_AT" \
    --arg sha256 "$(sha256sum <"$OMARCHY_OEM_EULA" | cut -d' ' -f1)" \
    '{oem: $oem, sha256: $sha256, accepted_by: $user, accepted_at: $at}' >/var/lib/omarchy/oem/eula-accepted.json
}

# Load the layout on the live VT and persist it for the installed system, or
# fail. systemd-firstboot writes the console KEYMAP and, for a keymap in
# kbd-model-map, the XKB layout Hyprland reads; omarchy_keymap_xkb_settings's
# lines stand in for one it writes none for, as the ISO's configure_keyboard
# does at install time. The boot files ask for the disk password in the layout
# vconsole.conf names, so a keymap localectl doesn't know, a failed loadkeys,
# or a file that does not read back as the chosen keymap with an XKB layout is
# a failure.
apply_keyboard() {
  local keymap=$1 keymaps saved

  if [[ $(tty 2>/dev/null) == /dev/tty* ]] && ! loadkeys "$keymap" >>"$LOG_FILE" 2>&1; then
    log_step "loadkeys could not load keymap $keymap"
    return 1
  fi

  if ! keymaps=$(localectl --no-pager list-keymaps 2>>"$LOG_FILE"); then
    log_step "localectl could not list keymaps to check $keymap"
    return 1
  fi
  if ! grep -qxF -- "$keymap" <<<"$keymaps"; then
    log_step "keymap $keymap unknown to localectl"
    return 1
  fi

  if ! systemd-firstboot --keymap="$keymap" --force >>"$LOG_FILE" 2>&1 &&
    ! localectl set-keymap "$keymap" >>"$LOG_FILE" 2>&1; then
    log_step "could not persist keymap $keymap"
    return 1
  fi

  # systemd-firstboot writes an XKB layout only for keymaps in kbd-model-map,
  # and several the form offers are not, so Hyprland would come up in US.
  if ! grep -q '^XKBLAYOUT=.' /etc/vconsole.conf 2>/dev/null; then
    omarchy_keymap_xkb_settings "$keymap" >>/etc/vconsole.conf 2>>"$LOG_FILE" ||
      log_step "no XKB layout known for keymap $keymap"
  fi

  # A clean shell, so nothing this process exported stands in for the file.
  saved=$(env -i /bin/bash --noprofile --norc -c \
    '. /etc/vconsole.conf && [[ -n ${XKBLAYOUT:-} ]] && printf %s "${KEYMAP:-}"' 2>>"$LOG_FILE") || saved=""
  if [[ $saved != "$keymap" ]]; then
    log_step "/etc/vconsole.conf does not read back as keymap $keymap with an XKB layout"
    return 1
  fi
}

# The account step, in the installer's order. The deferred install seeded
# neutral placeholders for the hostname and timezone (omarchy/UTC); the owner
# overwrites them here.
user_form() {
  step "$(omarchy_form_text setupForm.machineIntro)"

  omarchy_prompt_timezone || return $?

  # A prior attempt that already created the account pins the username, so a
  # retry cannot strand that account by choosing a different name.
  if [[ -f $PROVISIONING_DIR/setup-user ]]; then
    username=$(<"$PROVISIONING_DIR/setup-user")
    say "$(omarchy_form_text ownerSetup.continuing "$username")"
    echo
  else
    omarchy_prompt_username || return $?
  fi

  omarchy_prompt_password || return $?
  omarchy_generate_hostname
}

confirm_form() {
  step "$(omarchy_form_text setupForm.machineIntro)"
  omarchy_form_review "$PADDING_LEFT_SPACES"
}

# Groups recorded by omarchy-apply-system's scripts at install time
# (/var/lib/omarchy/provisioning/groups), filtered to groups that exist on this system.
user_groups() {
  local groups="sudo" group
  if [[ -f $PROVISIONING_DIR/groups ]]; then
    while IFS= read -r group; do
      [[ -n $group ]] || continue
      # Never replay old privileged group defaults. Docker is always opt-in.
      # Input is only retained when the factory image has one of the features
      # whose installer deliberately grants access to raw input devices.
      [[ $group == "docker" ]] && continue
      if [[ $group == "input" ]] &&
        ! pacman -Qq xpadneo-dkms &>/dev/null &&
        ! pacman -Qq ydotool &>/dev/null; then
        continue
      fi
      getent group "$group" >/dev/null || continue
      [[ ",$groups," == *",$group,"* ]] || groups+=",$group"
    done <"$PROVISIONING_DIR/groups"
  fi
  echo "$groups"
}

# Resolve the crypto_LUKS partition backing the root, or return non-zero if
# the root is not on LUKS. Prefers the cmdline cryptdevice= spec (archinstall
# writes PARTUUID=, the pre-mounted path UUID=), and falls back to walking the
# device tree for roots reached via rd.luks/crypttab with a plain /dev/mapper
# root and no cryptdevice=.
luks_device() {
  local spec
  spec=$(grep -o 'cryptdevice=[^ :]*' /proc/cmdline | head -1 | cut -d= -f2-)
  case $spec in
    UUID=*) echo "/dev/disk/by-uuid/${spec#UUID=}"; return 0 ;;
    PARTUUID=*) echo "/dev/disk/by-partuuid/${spec#PARTUUID=}"; return 0 ;;
    LABEL=*) echo "/dev/disk/by-label/${spec#LABEL=}"; return 0 ;;
    PARTLABEL=*) echo "/dev/disk/by-partlabel/${spec#PARTLABEL=}"; return 0 ;;
    /dev/*) echo "$spec"; return 0 ;;
  esac

  # No cryptdevice=: walk the root source's ancestors (lsblk -s inverts the
  # tree) for the first crypto_LUKS parent.
  local src part
  src=$(findmnt -no SOURCE / | sed 's/\[.*//')
  [[ -n $src ]] || return 1
  part=$(lsblk -nsrpo NAME,FSTYPE "$src" 2>/dev/null | awk '$2=="crypto_LUKS"{print $1; exit}')
  [[ -n $part ]] && { echo "$part"; return 0; }
  return 1
}

encrypted_install() {
  luks_device >/dev/null 2>&1
}

create_user() {
  # Pin the username so a retry after a later failure resumes this exact
  # account rather than creating a second privileged one.
  echo "$username" >"$PROVISIONING_DIR/setup-user"

  if getent passwd "$username" >/dev/null; then
    # Resuming a partially-completed earlier attempt: refresh what the form
    # collected this time around.
    usermod -aG "$(user_groups)" "$username"
  else
    useradd -m -G "$(user_groups)" -s /bin/bash "$username"
  fi

  printf '%s:%s\n' "$username" "$password" | chpasswd
  printf '%s:%s\n' root "$password" | chpasswd

  # deferred-provisioning installs skip archinstall's create_users, which is what normally
  # uncomments %wheel in /etc/sudoers. Always write the drop-in: detecting an
  # existing grant is error-prone (omarchy ships narrow %wheel NOPASSWD rules
  # for specific commands), and a duplicate grant is harmless.
  echo "%sudo ALL=(ALL:ALL) ALL" >/etc/sudoers.d/00-omarchy-wheel
  chmod 440 /etc/sudoers.d/00-omarchy-wheel

  source "$OMARCHY_PATH/install/helpers/browser-policy.sh"
  for dir in "${BROWSER_POLICY_MANAGED_DIRS[@]}"; do
    [[ -d $dir || -L $dir ]] || continue
    browser_policy_setup_dir "$dir"
  done
}

install_authorized_keys() {
  [[ -f $PROVISIONING_DIR/authorized_keys ]] || return 0

  local ssh_dir="/home/$username/.ssh"
  mkdir -p "$ssh_dir"
  cp "$PROVISIONING_DIR/authorized_keys" "$ssh_dir/authorized_keys"
  chmod 700 "$ssh_dir"
  chmod 600 "$ssh_dir/authorized_keys"
  chown -R "$username:$username" "$ssh_dir"
}

configure_login() {
  # Encrypted installs keep autologin permanently (the LUKS prompt is the auth
  # boundary). Unencrypted installs autologin only this first boot -- the owner
  # just authenticated in the form, so we don't make them retype at the login
  # screen -- then a one-shot service drops it so later boots show the login
  # screen and the disk isn't left permanently open.
  omarchy-system-login "$username" --autologin
  encrypted_install || install_autologin_once_cleanup
}

# Install a self-removing service that makes the autologin last exactly one
# boot — this one, where the owner just authenticated in the wizard. The unit is
# created now, but graphical.target's job for THIS boot is already computed, so
# it won't run this boot (this boot autologins). On the NEXT boot it's in the
# fresh transaction, ordered Before the display manager, so it runs before
# greetd reads its config: it drops the autologin (that boot shows the login
# screen) and deletes its own unit and enablement symlink. Ordering Before= (not
# After=) is what makes it deterministic — no sleep/race against greetd's
# startup.
install_autologin_once_cleanup() {
  local unit=omarchy-provision-autologin-once.service
  sed "s|@UNIT@|$unit|g" >"/etc/systemd/system/$unit" <<'UNIT'
[Unit]
Description=Drop the first-boot autologin before the next login
Before=display-manager.service

[Service]
Type=oneshot
ExecStart=/usr/bin/omarchy-system-login --no-autologin
ExecStartPost=/usr/bin/rm -f /etc/systemd/system/graphical.target.wants/@UNIT@ /etc/systemd/system/@UNIT@

[Install]
WantedBy=graphical.target
UNIT
  mkdir -p /etc/systemd/system/graphical.target.wants
  ln -sf "../$unit" "/etc/systemd/system/graphical.target.wants/$unit"
}

# The owner's language becomes the machine's preset, the way install media
# names one, once its locale exists; finalize_user then makes it the owner's
# desktop language. English is the absence of a preset. An earlier attempt may
# have seeded another language for the account, which nobody has logged in to
# choose, so that goes first.
configure_language() {
  local home
  home=$(getent passwd "$username" | cut -d: -f6)
  [[ -z $home ]] || rm -f "$home/.config/omarchy/language" "$home/.config/uwsm/env.d/50-omarchy-language"
  rm -f "$LANGUAGE_MARKER"
  [[ ${language:-en} != "en" ]] || return 0

  if "$OMARCHY_PATH/bin/omarchy-locale-generate" "$language" 2>&1; then
    mkdir -p "${LANGUAGE_MARKER%/*}"
    printf '%s\n' "$language" >"$LANGUAGE_MARKER"
  else
    log_step "could not generate the locale for $language; the desktop stays in English"
  fi
}

# Apply the owner's hostname, deferred to first boot with the rest of the user
# step, overwriting the placeholder the deferred install seeded.
configure_hostname() {
  [[ -n ${hostname:-} ]] || return 0
  hostnamectl set-hostname "$hostname" 2>&1 ||
    printf '%s\n' "$hostname" >/etc/hostname
}

# Apply the owner's timezone, deferred to first boot with the rest of the user
# step, overwriting the placeholder (UTC) the deferred install seeded.
configure_timezone() {
  [[ -n ${timezone:-} ]] || return 0
  if ! timedatectl set-timezone "$timezone" 2>&1; then
    # Fallback only if the zone file exists, so a bad zone can't point
    # /etc/localtime at nothing and break every localtime read afterward.
    [[ -e /usr/share/zoneinfo/$timezone ]] &&
      ln -sf "/usr/share/zoneinfo/$timezone" /etc/localtime 2>&1 || true
  fi
  configure_wireless_regdom
  configure_region
}

# A deferred install took its media's region before anyone chose a timezone,
# and left it as REGION in the form defaults: a market's code, or global from
# the global ISO. Settle it against the owner's choice: a timezone a region
# profile lists picks that region (global lists Hong Kong, Macau and Taiwan),
# and any other timezone keeps the media's region. Media that left no REGION
# keep whatever region the install wrote.
configure_region() {
  local defaults=${OMARCHY_FORM_DEFAULTS:-/etc/omarchy/form-defaults} marker=${OMARCHY_REGION_FILE:-/etc/omarchy/region}
  local pacman_conf=${OMARCHY_PACMAN_CONF:-/etc/pacman.conf} key value fallback="" region current=global profile channel
  [[ -r $defaults && -n ${timezone:-} ]] || return 0
  while IFS='=' read -r key value; do
    [[ $key == "REGION" ]] && fallback=$value
  done <"$defaults"
  [[ $fallback == "global" || $fallback =~ ^[a-z]{2}$ ]] || return 0
  region=$fallback
  for profile in "$OMARCHY_PATH"/default/regions/*/; do
    [[ -r $profile/timezones ]] && grep -qxF -- "$timezone" "$profile/timezones" && region=$(basename "$profile")
  done
  [[ -r $marker ]] && read -r current <"$marker"
  [[ $region == "$current" ]] && return 0
  if [[ $region == "global" ]]; then
    rm -f "$marker"
  else
    printf '%s\n' "$region" >"$marker"
  fi
  # The region's Node and npm mirrors, as an install would have set them.
  PATH="$OMARCHY_PATH/bin:$PATH" bash "$OMARCHY_PATH/install/config/region.sh" 2>&1 || true
  # Re-render pacman for the region with the channel this machine installed.
  channel=$(sed -n 's|^Server = https://pkgs\.omarchy\.[a-z]*/\([a-z]*\)/.*|\1|p' "$pacman_conf" | head -1)
  if [[ -n $channel && -x $OMARCHY_PATH/bin/omarchy-apply-pacman ]]; then
    "$OMARCHY_PATH/bin/omarchy-apply-pacman" "$channel" "${OMARCHY_REGION_TARGET:-/}" 2>&1 || true
  fi
}

# The install's hardware step found only the UTC placeholder, which names no
# country, so the wireless regulatory domain comes from the owner's timezone
# here. No reboot follows setup, so the radios get it now the way udev applies
# it at every boot.
configure_wireless_regdom() {
  bash "$OMARCHY_PATH/install/hardware/set-wireless-regdom.sh" 2>&1 || return 0
  if omarchy-cmd-present set-wireless-regdom; then
    set-wireless-regdom 2>&1 || true
  fi
}

finalize_user() {
  local home shell
  home=$(getent passwd "$username" | cut -d: -f6)
  shell=$(getent passwd "$username" | cut -d: -f7)

  runuser -u "$username" -- env \
    HOME="$home" \
    USER="$username" \
    LOGNAME="$username" \
    SHELL="${shell:-/bin/bash}" \
    OMARCHY_PATH="$OMARCHY_PATH" \
    OMARCHY_INSTALL="$OMARCHY_PATH/install" \
    OMARCHY_SETUP_CONTEXT=provision-owner \
    OMARCHY_INSTALL_LOG_FILE="$LOG_FILE" \
    OMARCHY_LOG_TO_STDOUT=1 \
    "$OMARCHY_PATH/bin/omarchy-provision-user" --force --first-install
}

# During the provisioning window the staged key rides in the UKI's initramfs,
# named on the kernel cmdline, so boot unlocks unattended.
PROVISIONING_UNLOCK_FILES=(
  /etc/omarchy/provisioning.key
  /etc/limine-entry-tool.d/99-omarchy-provisioning-unlock.conf
  /etc/cmdline.d/99-omarchy-provisioning-unlock.conf
  /etc/mkinitcpio.conf.d/99-omarchy-provisioning-key.conf
)

limine_auto_unlock_present() {
  local file
  for file in "${PROVISIONING_UNLOCK_FILES[@]}"; do
    [[ -e $file ]] && return 0
  done
  return 1
}

boot_backend() {
  "$OMARCHY_PATH/bin/omarchy-boot-backend"
}

# Rebuilds the boot images, on whichever loader this machine boots.
rebuild_boot_images() {
  if [[ $(boot_backend) == systemd-boot ]]; then
    "$OMARCHY_PATH/bin/omarchy-boot-rebuild" >>"$LOG_FILE" 2>&1
  else
    reset_limine_config
    limine-update >>"$LOG_FILE" 2>&1
  fi
}

# Rebuild the UKI without the embedded keyfile. A failed rebuild restores the
# auto-unlock, so the retry still boots unattended.
limine_auto_unlock_drop() {
  rm -f "${PROVISIONING_UNLOCK_FILES[@]}"
  if rebuild_boot_images; then
    return 0
  fi

  # Once the staged key is destroyed there is no auto-unlock to restore: the
  # boot files already ask for the owner's password. The rebuild is still
  # retried for the boot entries.
  if [[ -f $PROVISIONING_DIR/luks-key ]]; then
    log_step "the boot image rebuild failed during re-key; restoring auto-unlock for retry"
    install -Dm600 "$PROVISIONING_DIR/luks-key" /etc/omarchy/provisioning.key
    if [[ $(boot_backend) == systemd-boot ]]; then
      mkdir -p /etc/cmdline.d
      echo 'cryptkey=rootfs:/etc/omarchy/provisioning.key' >/etc/cmdline.d/99-omarchy-provisioning-unlock.conf
    else
      echo 'KERNEL_CMDLINE[default]+=" cryptkey=rootfs:/etc/omarchy/provisioning.key"' \
        >/etc/limine-entry-tool.d/99-omarchy-provisioning-unlock.conf
    fi
    echo 'FILES+=(/etc/omarchy/provisioning.key)' >/etc/mkinitcpio.conf.d/99-omarchy-provisioning-key.conf
  else
    log_step "the boot image rebuild failed during re-key; the staged key is gone, so no auto-unlock is restored"
  fi
  rebuild_boot_images || true
  return 1
}

# A platform whose boot package implements provision-commit and provision-verify
# stages the unlock in its own boot chain and owns it; everywhere else it rides
# in the Limine UKI above. Deciding fails closed: the unlock then counts as
# present and cannot be dropped.
UNLOCK_OWNER=""

unlock_owner() {
  [[ -z ${UNLOCK_OWNER:-} ]] || return 0

  local commit verify
  commit=$("$OMARCHY_PATH/bin/omarchy-lifecycle-dispatch" --resolve provision-commit) || return 1
  verify=$("$OMARCHY_PATH/bin/omarchy-lifecycle-dispatch" --resolve provision-verify) || return 1
  if [[ -n $commit && -n $verify ]]; then
    UNLOCK_OWNER=platform
  elif [[ -z $commit && -z $verify ]]; then
    UNLOCK_OWNER=limine
  else
    log_step "the platform implements only one of provision-commit and provision-verify"
    return 1
  fi
}

luks_auto_unlock_present() {
  unlock_owner || return 0
  if [[ $UNLOCK_OWNER == "platform" ]]; then
    ! "$OMARCHY_PATH/bin/omarchy-lifecycle-dispatch" provision-verify >>"$LOG_FILE" 2>&1
  else
    limine_auto_unlock_present
  fi
}

luks_auto_unlock_drop() {
  unlock_owner || return 1
  if [[ $UNLOCK_OWNER == "platform" ]]; then
    "$OMARCHY_PATH/bin/omarchy-lifecycle-dispatch" provision-commit >>"$LOG_FILE" 2>&1
  else
    limine_auto_unlock_drop
  fi
}

# The platform records the slot the re-key keeps, and no recovery slot; a no-op
# where nothing does.
luks_record_slots() {
  "$OMARCHY_PATH/bin/omarchy-lifecycle-dispatch" luks-slots "owner=$1" "recovery=" >>"$LOG_FILE" 2>&1
}

# Move the LUKS volume from the throwaway install passphrase to the user's
# password and retire every other slot (throwaway + any seller keys a reset
# left behind). luks_rekey journals each step, so an interrupted attempt
# resumes where it stopped.
rekey_luks() {
  luks_rekey_pending || return 0

  local device
  if ! device=$(luks_device) || [[ ! -e $device ]]; then
    log_step "cannot locate the LUKS device from /proc/cmdline: $(cat /proc/cmdline)"
    say --foreground 1 "Could not locate the LUKS device to re-key."
    return 1
  fi

  luks_rekey "$device"
}

# The re-key's fingerprint of the console keyboard layout the boot files ask for
# the disk password in: a hash of vconsole.conf's keymap and XKB settings, in
# file order since a later duplicate wins, so the journal never names the layout.
luks_boot_layout() {
  if [[ ! -f /etc/vconsole.conf ]]; then
    echo none
    return
  fi
  awk '/^[ \t]*(KEYMAP|KEYMAP_TOGGLE|XKB[A-Z_]*)=/ { sub(/^[ \t]+/, ""); print }' /etc/vconsole.conf |
    sha256sum | cut -d' ' -f1
}

# A re-key interrupted after the staged key was retired can only finish with
# the password the disk already holds.
rekey_accepts_password() {
  local -
  set +x
  local device
  [[ -f $REKEY_STATE ]] || return 0
  if ! device=$(luks_device) || [[ ! -e $device ]]; then
    return 0
  fi
  luks_rekey_accepts_password "$device"
}

# Start the ESP's limine.conf settings over from the shipped template before
# rebuilding this machine's boot entry. limine-entry-tool keys OS entries by
# machine-id, and an entry rebuilt on top of stale kernel entries would keep a
# stale UKI hash and make Limine stop at a hash-mismatch warning.
esp_path() {
  local esp=""
  if [[ -f /etc/default/limine ]]; then
    esp=$(sed -n 's/^ESP_PATH=["'\'']\?\([^"'\'']*\).*/\1/p' /etc/default/limine | tail -1)
  fi
  echo "${esp:-/boot}"
}

# Stale only if this machine has no bootable entry of its own: none at all,
# or the bare header reset_limine_config leaves when the rebuild after it
# failed. Other machine-ids are not stale: a shared ESP holds other systems'
# entries, and the factory reset already re-keyed this system's entry to the
# identity it boots with. A machine on systemd-boot has no Limine entry: a
# limine.conf on its ESP is another installation's.
limine_entries_stale() {
  local esp machine_id
  [[ $(boot_backend) != systemd-boot ]] || return 1
  esp=$(esp_path)
  machine_id=$(cat /etc/machine-id 2>/dev/null || true)
  [[ -f $esp/limine.conf && -n $machine_id ]] || return 1
  ! awk -v id="$machine_id" '
    /^\/[^\/]/ { mine = 0 }
    $0 ~ ("^comment: machine-id=" id "([[:space:]]|$)") { mine = 1 }
    mine && /^[[:space:]]*[a-z_]*path:/ { bootable = 1 }
    END { exit !bootable }
  ' "$esp/limine.conf"
}

# Only this machine's own entry is emptied for limine-update to rebuild in
# place, where default_entry points. Every other entry and machine-id
# directory stays: on a shared ESP they belong to other systems (Windows,
# other Linux installs), and nothing here can tell them from our own leftovers.
reset_limine_config() {
  local esp template="" candidate machine_id entries=""
  esp=$(esp_path)

  for candidate in "$OMARCHY_PATH/install/assets/limine/limine.conf" \
                   "$OMARCHY_PATH/default/limine/limine.conf"; do
    if [[ -f $candidate ]]; then
      template=$candidate
      break
    fi
  done
  if [[ -z $template ]]; then
    log_step "no limine.conf template found; keeping the existing config"
    return 0
  fi

  machine_id=$(cat /etc/machine-id 2>/dev/null || true)
  if [[ -f $esp/limine.conf ]]; then
    # Same rewrite as omarchy-system-factory-reset, keyed to this identity:
    # this machine's entry keeps only its header, and any copy after the first
    # is dropped. A fresh image's Omarchy entry has no machine-id yet; it is
    # keyed to this one in place, so limine-update rebuilds it where default_entry points.
    entries=$(awk -v id="$machine_id" '
      function flush() {
        image = id != "" && !has_id && image_entry && image_uki
        if (image && !kept) { printf "%scomment: machine-id=%s order-priority=50\n\n", header, id; kept = 1 }
        else if (is_ours && !kept) { printf "%s\n", header; kept = 1 }
        else if (!is_ours && !image) printf "%s", block
        block = header = ""; is_ours = nested = has_id = image_entry = image_uki = 0
      }
      /^\/[^\/]/ { flush(); in_entry = 1 }
      !in_entry { next }
      {
        if ($0 == "/+Omarchy") image_entry = 1
        if (/^comment: machine-id=/) has_id = 1
        if (/^[[:space:]]*path: boot\(\):\/EFI\/Linux\/omarchy_/) image_uki = 1
        if (id != "" && /^comment: machine-id=/ && $0 ~ ("machine-id=" id "([[:space:]]|$)")) is_ours = 1
        if (/^[[:space:]]*\/\//) nested = 1
        block = block $0 "\n"
        if (!nested) header = header $0 "\n"
      }
      END { flush() }
    ' "$esp/limine.conf")
  fi

  { cat "$template"; [[ -z $entries ]] || printf '%s\n' "$entries"; } >"$esp/limine.conf.new"
  mv "$esp/limine.conf.new" "$esp/limine.conf"
}

cleanup_oem_state() {
  rm -f "$PROVISIONING_DIR/pending" "$PROVISIONING_DIR/authorized_keys" "$PROVISIONING_DIR/setup-user" \
    "$PROVISIONING_DIR/luks-calibration.json" "$REKEY_STATE"

  rm -f /etc/systemd/system/multi-user.target.wants/omarchy-provision-owner.service
  systemctl daemon-reload 2>/dev/null || true
}

# The provisioning work, backgrounded under the progress screen. Phase writes
# to STATE_FILE drive the progress; all output lands in the log.
run_provisioning() {
  log_step "creating user $username"
  create_user
  record_eula
  install_authorized_keys
  configure_login

  log_step "setting language to ${language:-en}"
  configure_language

  log_step "setting hostname to ${hostname:-omarchy}"
  configure_hostname

  log_step "setting timezone to ${timezone:-UTC}"
  configure_timezone

  log_step "finalizing user"
  echo finalize >"$STATE_FILE"
  if ! finalize_user; then
    log_step "finalize-user failed (continuing)"
    touch "$FINALIZE_WARNING_FLAG"
  fi

  if luks_rekey_pending; then
    log_step "re-keying LUKS to the user's password"
    echo rekey >"$STATE_FILE"
    rekey_luks
    log_step "LUKS re-key complete"
  fi

  # On an unencrypted machine nothing above rebuilds the boot entries. The
  # factory reset already keyed them to this identity, so this only repairs a
  # machine left without an entry of its own.
  if limine_entries_stale; then
    log_step "refreshing boot entries for the new machine identity"
    echo boot >"$STATE_FILE"
    reset_limine_config
    limine-update
  fi

  if luks_staged_unlock_remains; then
    log_step "refusing to finish setup while the staged LUKS key or its auto-unlock remains"
    return 1
  fi

  log_step "cleaning up provisioning state"
  cleanup_oem_state
  log_step "first-boot setup complete"
}

# Where the platform's boot package owns the boot chain, it must be ready to
# finish setup, and able to record the kept key slot, before the owner is asked
# anything.
platform_ready() {
  local error
  if error=$("$OMARCHY_PATH/bin/omarchy-lifecycle-dispatch" provision-prepare 2>&1 >>"$LOG_FILE") &&
    error=$("$OMARCHY_PATH/bin/omarchy-lifecycle-dispatch" --resolve luks-slots 2>&1 >/dev/null); then
    return 0
  fi
  error=${error:-"The boot package could not prepare this machine for setup."}

  log_step "the boot package is not ready for setup: $error"
  clear_logo
  echo
  say --foreground 1 "$error"
  sleep 5
  return 1
}

run_setup() {
  local status

  platform_ready || return 1

  # Each attempt is its own process, so it learns for itself what the font draws.
  fit_console_font
  if [[ -r $KMSCON_RESUME ]]; then
    # shellcheck disable=SC1090
    source "$KMSCON_RESUME"
    rm -f "$KMSCON_RESUME"
    omarchy_form_use_language "$language"
  else
    initial_language
    language_form
    keyboard_form || return 1
  fi

  while true; do
    user_form && status=0 || status=$?
    if ((status == OMARCHY_FORM_SIGNAL)); then
      # Ctrl+C offers the reboot; declined, the account step starts over.
      confirm_reboot && exec systemctl reboot
      continue
    elif ((status != 0)); then
      # Esc unwinds to the keyboard step.
      keyboard_form || return 1
      continue
    fi

    # "No, change it" starts over from the language, as in the installer.
    if ! confirm_form; then
      language_form
      keyboard_form || return 1
      continue
    fi
    if ! rekey_accepts_password; then
      notice "$(omarchy_form_text ownerSetup.samePassword)" 4
      continue
    fi
    # Esc on the agreement unwinds to the keyboard, as it does from the account.
    if ! eula_form; then
      keyboard_form || return 1
      continue
    fi
    break
  done

  load_tips

  touch "$LOG_FILE"
  chmod 600 "$LOG_FILE"

  rm -f "$FINALIZE_WARNING_FLAG"
  echo account >"$STATE_FILE"

  run_provisioning >>"$LOG_FILE" 2>&1 &
  local worker=$!

  set_now
  SETUP_T0=$NOW
  SETUP_PHASE_T0=$NOW

  render_setup_static
  # Read the phase and the log at 2 Hz; animate the trace at 10 Hz, as the ISO
  # install dashboard does.
  local frame=0
  while kill -0 "$worker" 2>/dev/null; do
    render_setup_dynamic "$((frame % 5 == 0))"
    frame=$((frame + 1))
    sleep 0.1
  done

  # The cursor comes back only on the failure path, where the retry prompt needs
  # it. A clean run keeps it hidden through the last frame and the handoff.
  local status=0
  wait "$worker" || status=$?
  if (( status != 0 )); then
    printf '%s' "$SHOW_CURSOR"
    return "$status"
  fi

  # Finish the trace and show the solid icon, so the handoff doesn't cut in
  # mid-progress.
  echo done >"$STATE_FILE"
  render_setup_finish
  # Ahead of the pause, so the picture is ready to follow kmscon at once.
  [[ -f $FINALIZE_WARNING_FLAG ]] || record_finished_icon
  sleep 1

  if [[ -f $FINALIZE_WARNING_FLAG ]]; then
    rm -f "$FINALIZE_WARNING_FLAG"
    clear_logo
    echo
    say --foreground 1 "$(omarchy_form_text ownerSetup.finalizeWarning "$LOG_FILE")"
    sleep 3
  fi

  # Deferred first boot hands straight off to the display manager: greetd starts
  # the moment this oneshot exits (Before=display-manager.service) and autologs
  # in on encrypted installs. No timed celebration screen and no "start" button
  # here — that send-off belongs to a direct install, not first-boot setup. The
  # finished progress bar is the last frame; clearing it for a "Starting
  # Omarchy..." card would only add a flash of screen before the handoff.
}

# The finished icon is setup's last frame, and it stays on screen until the
# desktop is up: setup paints it on the console as kmscon goes
# (show_finished_icon), and leaves that picture for the owner's first login,
# which adopts it (uwsm's env.d/10-omarchy) and shows it in its startup cover
# until the desktop is ready (omarchy-launch-shell, shell/startup-cover.qml).
# Only a nicety: nothing here may fail setup.
record_finished_icon() {
  local width height cell="" pixels mode=""
  # The console's visible size: its mode, as "U:1280x800p-0", else its whole
  # framebuffer, which can be allocated taller.
  { read -r mode </sys/class/graphics/fb0/modes; } 2>/dev/null || true
  if [[ $mode =~ ^[A-Z]:([0-9]+)x([0-9]+) ]]; then
    width=${BASH_REMATCH[1]} height=${BASH_REMATCH[2]}
  else
    { IFS=, read -r width height </sys/class/graphics/fb0/virtual_size; } 2>/dev/null || return 0
  fi
  [[ $width =~ ^[0-9]+$ && $height =~ ^[0-9]+$ ]] || return 0
  cell=$(omarchy_kmscon_cell_size "$KMSCON_STATE/kmscon.log") || true
  # shellcheck disable=SC2086 # the cell's two numbers, or none
  pixels=$(progress_icon_pixels "$width" "$height" $cell) || return 0
  # Whole or not at all, as the painter reads it once it is there.
  echo "$width $height $pixels $username" >"$FINISHED_ICON.new" && mv -f "$FINISHED_ICON.new" "$FINISHED_ICON" || true
}

# Once kmscon has gone, the console would show until the login takes the
# display: paint the finished icon where kmscon drew it, in kmscon's colours
# (install/provisioning/kmscon.sh) and without the text, straight onto the
# framebuffer, with the console in graphics mode so its text never draws over
# it. greetd leaves that mode as it is (omarchy-system-login). kmscon hands the
# console back well before it exits, and the console draws itself then, so this
# runs beside kmscon: it gets the picture ready once setup has recorded it
# (record_finished_icon) and paints it the moment the console is back, or when
# told kmscon has gone (FINISHED_ICON_GO). The same picture then goes to the
# owner, as the one file their first login looks for.
show_finished_icon() {
  local console=$1 owner home
  [[ -w /dev/fb0 && $console == /dev/tty* ]] || return 0
  owner=$(python3 -I - "$console" "$FINISHED_ICON" "$FINISHED_ICON_GO" "${ICON_MASK[@]}" 2>>"$LOG_FILE" <<'PY'
import fcntl, math, mmap, os, struct, sys, time, zlib

tty, icon_file, go, mask = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4:]
KDSETMODE, KDGETMODE, KD_TEXT, KD_GRAPHICS = 0x4B3A, 0x4B3B, 0, 1
background, color = bytes.fromhex("1a1b26"), bytes.fromhex("9ece6a")

# Setup's finished icon, which comes only once it has finished.
while not os.path.exists(icon_file):
  if os.path.exists(go):
    sys.exit(1)
  time.sleep(0.05)
with open(icon_file) as f:
  icon = f.read().split()
os.unlink(icon_file)
width, height, left, top, column, row = (float(n) for n in icon[:6])
owner = icon[6]

fb = os.open("/dev/fb0", os.O_RDWR)
# fb_var_screeninfo: the resolution, the depth and where each channel sits.
var = fcntl.ioctl(fb, 0x4600, bytes(160))  # FBIOGET_VSCREENINFO
xres, yres = struct.unpack_from("II", var)
bits, = struct.unpack_from("I", var, 24)
red, green, blue = (struct.unpack_from("I", var, offset)[0] for offset in (32, 44, 56))
if bits != 32 or (xres, yres) != (int(width), int(height)):
  sys.exit(f"show_finished_icon: a {xres}x{yres} {bits}-bit framebuffer is not the {int(width)}x{int(height)} console kmscon drew on")
with open("/sys/class/graphics/fb0/stride") as f:
  stride = int(f.read())

def edge(n):
  return math.floor(n + 0.5)

# The icon's squares as [x0, x1) x [y0, y1) rectangles of the console's pixels.
squares = [(edge(left + x * column), edge(left + (x + 1) * column), edge(top + y * row), edge(top + (y + 1) * row))
           for y, line in enumerate(mask) for x, filled in enumerate(line) if filled == "1"]

def picture(back, fore, line_length):
  image = bytearray(back * xres).ljust(line_length, b"\0") * yres
  for x0, x1, y0, y1 in squares:
    for y in range(y0, y1):
      start = y * line_length + x0 * len(fore)
      image[start:start + (x1 - x0) * len(fore)] = fore * (x1 - x0)
  return image

def pixel(rgb):
  value = rgb[0] << red | rgb[1] << green | rgb[2] << blue
  return struct.pack("<I", value | (0xFF << 24 if 24 not in (red, green, blue) else 0))

frame = bytes(picture(pixel(background), pixel(color), stride))
screen = mmap.mmap(fb, stride * yres)

# The top left square's middle, in the icon's colour or not.
probe = edge(top + row / 2) * stride + edge(left + column / 2) * 4
channels = struct.pack("<I", 0xFF << red | 0xFF << green | 0xFF << blue)
def shows_icon():
  return all(a & m == b & m for a, b, m in zip(screen[probe:probe + 4], pixel(color), channels))

# kmscon keeps the console in graphics mode until it lets go of it. Drawing on
# /dev/fb0 itself (--no-drm), it clears the screen first, so the icon goes
# back the moment it does; drawing through DRM, /dev/fb0 isn't on screen until
# kmscon has gone, and painting it early shows nothing.
console = os.open(tty, os.O_RDWR)
mode = bytearray(4)
while not os.path.exists(go):
  fcntl.ioctl(console, KDGETMODE, mode)
  if struct.unpack("i", mode)[0] == KD_TEXT:
    break
  if not shows_icon():
    screen[:] = frame
  time.sleep(0.002)
fcntl.ioctl(console, KDSETMODE, KD_GRAPHICS)
screen[:] = frame

# The same picture as a PNG, for the owner's first login.
rgb = picture(background, color, xres * 3)
rows = b"".join(b"\0" + rgb[y * xres * 3:(y + 1) * xres * 3] for y in range(yres))
def chunk(kind, body):
  return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body))
with open(icon_file + ".png", "wb") as f:
  f.write(b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", xres, yres, 8, 2, 0, 0, 0))
          + chunk(b"IDAT", zlib.compress(rows, 1)) + chunk(b"IEND", b""))
print(owner)
PY
  ) || return 0
  home=$(getent passwd "$owner" | cut -d: -f6) && [[ -n $home ]] &&
    runuser -u "$owner" -- install -D -m 644 "$FINISHED_ICON.png" "$home/.local/state/omarchy/setup-cover.png" || true
  rm -f "$FINISHED_ICON.png"
}

# A failed first-boot setup must not strand the machine at a user-less login
# screen. Each attempt runs as its own process — bash ignores errexit inside
# `while !` conditions, but a child process keeps its own set -e — and failure
# offers a retry; create_user and friends are idempotent, so retrying is safe.
if [[ ${1:-} == "--attempt" ]]; then
  run_setup
  exit 0
fi

main() {
  local status keymap painter

  # The whole of setup runs in kmscon on this VT, started again for as long as
  # setup is not done: an attempt asks for that with KMSCON_RESUME, and the
  # login screen must not start on a machine that still has no owner. Leaving for the root
  # shell or a reboot ends it.
  if [[ ${OMARCHY_KMSCON:-} != 1 ]]; then
    # A dark, empty console behind kmscon, for the moments it is not drawing.
    set_tokyo_night_colors
    mkdir -p "$KMSCON_STATE"
    while [[ -f $PROVISIONING_DIR/pending && ! -e $KMSCON_STATE/shell ]] &&
      [[ $(systemctl is-system-running 2>/dev/null) != stopping ]]; do
      initial_language
      # The keymap the console is in: the image's, or the one setup just set.
      keymap=$(. /etc/vconsole.conf 2>/dev/null; printf '%s' "${KEYMAP:-us}")
      rm -f "$FINISHED_ICON" "$FINISHED_ICON_GO"
      # In the background its input is not the console, so it is told which.
      show_finished_icon "$(tty)" &
      painter=$!
      omarchy_kmscon "$KMSCON_STATE/kmscon.log" "$keymap" "$language" "$OMARCHY_OEM_COLOR" "$0"
      touch "$FINISHED_ICON_GO"
      wait "$painter" || true
    done
    exit 0
  fi

  # Font sizing waits for the console to settle, so it lives inside
  # greeter_screen (which owns that settle) rather than running here on a VT
  # that may still be in a transitional mode this early in first boot.
  set_tokyo_night_colors
  # A relaunch of kmscon is the same setup carrying on, not a new start.
  [[ -e $KMSCON_RESUME ]] || greeter_screen

  while true; do
    "$0" --attempt && break || status=$?
    ((status == KMSCON_RELAUNCH)) && [[ -e $KMSCON_RESUME ]] && exit 0
    # In the language the failed attempt was in.
    initial_language
    clear_logo
    echo
    say --foreground 1 "$(omarchy_form_text ownerSetup.failed "$LOG_FILE")"
    echo
    if ! gum confirm --affirmative "$(omarchy_form_text ownerSetup.retryYes)" --negative "$(omarchy_form_text ownerSetup.retryNo)" \
      "$(omarchy_form_text ownerSetup.retryPrompt)"; then
      # Give an actual usable console: this service owns tty1 (and Conflicts the
      # getty), and on a failed deferred setup there's no user account and root
      # is locked — so exiting would strand the machine with no way in. Exec a
      # root shell on tty1; greetd starts once it exits.
      say "Dropping to a root shell. Run 'omarchy-provision-owner' to retry setup."
      touch "$KMSCON_STATE/shell"
      exec /bin/bash
    fi
  done
}

main
