#!/usr/bin/env bash
# DIY Platform — workstation setup for Linux.
#
# Turns a fresh Linux machine into one that can run DIY Platform and build the
# kinds of projects it makes: the app and its agent tools, the agent service,
# the coding-agent CLIs, the language toolchains, Docker for the databases the
# app starts, the system libraries a Tauri / Rust / audio build needs, and
# WhisperKey, offline voice dictation for every application on the machine.
#
#   curl -fsSL https://install.vibedout.app/diy-setup.sh | bash
#   curl -fsSL https://install.vibedout.app/diy-setup.sh | bash -s -- --check
#   bash diy-setup.sh --skip docker,agents      # leave some sections out
#   bash diy-setup.sh --only app                # just (re)install the app
#   bash diy-setup.sh --agents gemini,opencode  # these extra coding agents, besides the three that are always installed
#                     (Claude Code, Codex and the Antigravity CLI come with every run; extras: gemini pi opencode, default: gemini and pi)
#   bash diy-setup.sh --with android,images,flutter   # add the optional sections
#   bash diy-setup.sh --build-machine                 # also make this a build machine for DIY's lanes (the same as --with worker)
#
# Sections, in order:
#   system      compilers, Tauri/WebKitGTK libs, Vulkan, audio, Python, git, jq …   (sudo)
#   gpu         whether the graphics card is really in use (a kernel driver bound to it AND a real Vulkan device for it). Says plainly
#               when it is not: WhisperKey's and vibedout Terminal's speech models then run on the CPU. A missing NVIDIA driver is offered
#               with `ubuntu-drivers install` on Ubuntu (asks first; DIY_GPU_DRIVER=install|skip answers for you), and shown as the exact
#               RPM Fusion / pacman commands on Fedora and Arch: never installed behind your back, it needs a restart (and a key to enrol
#               with Secure Boot). A virtual machine's adapter is said to be what it is: no GPU.
#   session     (user level) so that one program killed for lack of memory does not close DIY Platform and every terminal in it
#               (a systemd drop-in for the scope DIY is started in from its launcher); a note about GNOME's Force Quit wait
#   node        Node.js 24 via nvm (diy-agentd needs 22.19+, n8n needs 24), pnpm, bun
#   rust        rustup + the stable toolchain
#   python      uv (Python projects and tools)
#   docker      Docker Engine + compose; you are added to the docker group    (sudo)
#   agents      Claude Code, Codex and the Antigravity CLI (agy), always; Gemini CLI and pi, or the extras --agents names; herdr
#   cli         gh, wrangler, supabase, hindsight, arduino-cli
#   app         DIY Platform (.deb, .rpm or AppImage) + its MCP server, `diy` CLI,
#               diyd, diy-agentd, offline voice, n8n and graft; registers the MCP
#               server with Claude; sets up the diy-agentd user service (systemd
#               --user: started now and at every login)
#   celld       celld, esbuild and weed, for Cloudflare Workers projects that run on this machine with no Cloudflare account: pinned by
#               sha256 (celld's build attestation checked when gh is there), into ~/.local/lib/diy/celld, no root. Nothing is
#               started here: the bucket and each app are user units that `diy-celld app install` makes. DIY OS has them in its image.
#   whisperkey  WhisperKey, if it is not there yet: offline dictation in every
#               application (press Ctrl+Space, speak, press it again). The .deb
#               or .rpm when the distro has one, else the AppImage; it starts
#               with your session, and its speech model (488 MB) is downloaded
#               now. Skipped on a machine with no desktop.
#   android     (optional) a JDK + Rust Android targets — the app fetches the SDK
#   images      (optional) pre-pull the Docker images the app starts on demand
#   flutter     (optional) the Flutter SDK (stable) + what its Linux desktop target needs
#   worker      (optional, --build-machine) a build machine for DIY's lanes: setup-linux.sh (51.40), as root, after the rest: the
#               toolchains DIY's builds need and a diy-worker user that signs in by key only. Ubuntu, Debian and Fedora. It is the
#               copy the app's tools carry (~/.local/share/diy-platform/tools/worker), else $SITE/worker/setup-linux.sh. Joining it to
#               your DIY is a step of its own: diy worker add <this machine> on your DIY, then setup-linux.sh --join here.
#
# Every step checks first and skips what is already there, so it is safe to run
# again: re-running is also how you upgrade DIY Platform to the newest release
# (and WhisperKey, when a package manager or this script installed it). One failed step does not stop
# the others; the summary at the end lists it.
#
# Supported: Debian/Ubuntu/Mint/Pop!_OS (apt), Fedora (dnf), Arch/Manjaro
# (pacman). x86_64. Run as your normal user, not root — it asks for sudo when a
# section needs it.
#
# Environment overrides: DIY_NODE_MAJOR (default 24), DIY_SITE (default
# https://install.vibedout.app), DIY_SKIP_VOICE / DIY_SKIP_AUTOMATION /
# DIY_SKIP_GRAFT=1 (passed through to the app's tool installer), DIY_TOOLS_TARBALL +
# DIY_APP_VERSION (a local agent-tools tarball and the app version it belongs to),
# DIY_SKIP_AGENTD=1 (no diy-agentd user service; DIY_AGENTS_ROOT, DIY_API_PORT and
# DIY_AGENTD_PORT, when set, go into its unit), DIY_SKIP_CELLD=1 (no celld, esbuild and weed;
# DIY_CELLD_ATTEST=require makes the attestation check mandatory), DIY_SKIP_WHISPERKEY=1 (no
# WhisperKey), DIY_WHISPERKEY=1 (install it even where no desktop is found),
# DIY_WHISPERKEY_MODEL=0 (leave the speech model to WhisperKey's first start), DIY_GPU_DRIVER=install|skip|ask (the GPU
# section's question; ask = the default, which needs a terminal and otherwise does not install).
set -uo pipefail

# Everything runs from main, called on the last line: a download cut short (curl | bash) is a syntax error and runs nothing (51.40 review 1).
# The last line passes --end-of-script after the arguments: a cut inside that line, even at `main` itself, runs nothing (review 2, N6).
main() {
if [ "$#" -eq 0 ] || [ "${!#}" != --end-of-script ]; then
  echo "diy-setup.sh: this copy is cut short (the download did not finish): nothing was done. Download it again." >&2
  exit 1
fi
set -- "${@:1:$#-1}"

SITE="${DIY_SITE:-https://install.vibedout.app}"
NODE_MAJOR="${DIY_NODE_MAJOR:-24}"
ALL_SECTIONS="system gpu session node rust python docker agents cli app celld whisperkey"
OPTIONAL_SECTIONS="android images flutter worker"

# ── output ──

if [ -t 1 ]; then B=$'\e[1m'; G=$'\e[32m'; Y=$'\e[33m'; R=$'\e[31m'; D=$'\e[2m'; N=$'\e[0m'; else B= G= Y= R= D= N=; fi
say()  { printf '%s\n' "$*"; }
head_() { printf '\n%s── %s ──%s\n' "$B" "$*" "$N"; }
ok()   { printf '  %s✓%s %s\n' "$G" "$N" "$*"; }
todo() { printf '  %s→%s %s\n' "$Y" "$N" "$*"; }
bad()  { printf '  %s✗%s %s\n' "$R" "$N" "$*" >&2; }
FAILED=()
MISSING=()
fail() { bad "$*"; FAILED+=("$*"); }

usage() { # the header above, also when the script is piped (there is no file to read then)
  cat <<'USAGE'
DIY Platform — workstation setup for Linux.

Turns a fresh Linux machine into one that can run DIY Platform and build the
kinds of projects it makes: the app and its agent tools, the agent service,
the coding-agent CLIs, the language toolchains, Docker for the databases the
app starts, the system libraries a Tauri / Rust / audio build needs, and
WhisperKey, offline voice dictation for every application on the machine.

  curl -fsSL https://install.vibedout.app/diy-setup.sh | bash
  curl -fsSL https://install.vibedout.app/diy-setup.sh | bash -s -- --check
  bash diy-setup.sh --skip docker,agents      # leave some sections out
  bash diy-setup.sh --only app                # just (re)install the app
  bash diy-setup.sh --agents gemini,opencode  # these extra coding agents, besides the three that are always installed
                    (Claude Code, Codex and the Antigravity CLI come with every run; extras: gemini pi opencode, default: gemini and pi)
  bash diy-setup.sh --with android,images,flutter   # add the optional sections
  bash diy-setup.sh --build-machine                 # also make this a build machine for DIY's lanes (the same as --with worker)

Sections, in order:
  system      compilers, Tauri/WebKitGTK libs, Vulkan, audio, Python, git, jq …   (sudo)
  gpu         whether the graphics card is really in use (a kernel driver bound to it AND a real Vulkan device for it). Says plainly
              when it is not: WhisperKey's and vibedout Terminal's speech models then run on the CPU. A missing NVIDIA driver is offered
              with `ubuntu-drivers install` on Ubuntu (asks first; DIY_GPU_DRIVER=install|skip answers for you), and shown as the exact
              RPM Fusion / pacman commands on Fedora and Arch: never installed behind your back, it needs a restart (and a key to enrol
              with Secure Boot). A virtual machine's adapter is said to be what it is: no GPU.
  session     (user level) so that one program killed for lack of memory does not close DIY Platform and every terminal in it
              (a systemd drop-in for the scope DIY is started in from its launcher); a note about GNOME's Force Quit wait
  node        Node.js 24 via nvm (diy-agentd needs 22.19+, n8n needs 24), pnpm, bun
  rust        rustup + the stable toolchain
  python      uv (Python projects and tools)
  docker      Docker Engine + compose; you are added to the docker group    (sudo)
  agents      Claude Code, Codex and the Antigravity CLI (agy), always; Gemini CLI and pi, or the extras --agents names; herdr
  cli         gh, wrangler, supabase, hindsight, arduino-cli
  app         DIY Platform (.deb, .rpm or AppImage) + its MCP server, `diy` CLI,
              diyd, diy-agentd, offline voice, n8n and graft; registers the MCP
              server with Claude; sets up the diy-agentd user service (systemd
              --user: started now and at every login)
  celld       celld, esbuild and weed, for Cloudflare Workers projects that run on this machine with no Cloudflare account: pinned by
              sha256 (celld's build attestation checked when gh is there), into ~/.local/lib/diy/celld, no root. Nothing is
              started here: the bucket and each app are user units that `diy-celld app install` makes. DIY OS has them in its image.
  whisperkey  WhisperKey, if it is not there yet: offline dictation in every
              application (press Ctrl+Space, speak, press it again). The .deb
              or .rpm when the distro has one, else the AppImage; it starts
              with your session, and its speech model (488 MB) is downloaded
              now. Skipped on a machine with no desktop.
  android     (optional) a JDK + Rust Android targets — the app fetches the SDK
  images      (optional) pre-pull the Docker images the app starts on demand
  flutter     (optional) the Flutter SDK (stable) + what its Linux desktop target needs
  worker      (optional, --build-machine) a build machine for DIY's lanes: setup-linux.sh (51.40), as root, after the rest: the
              toolchains DIY's builds need and a diy-worker user that signs in by key only. Ubuntu, Debian and Fedora. It is the
              copy the app's tools carry (~/.local/share/diy-platform/tools/worker), else $SITE/worker/setup-linux.sh. Joining it to
              your DIY is a step of its own: diy worker add <this machine> on your DIY, then setup-linux.sh --join here.

Every step checks first and skips what is already there, so it is safe to run
again: re-running is also how you upgrade DIY Platform to the newest release
(and WhisperKey, when a package manager or this script installed it). One failed step does not stop
the others; the summary at the end lists it.

Supported: Debian/Ubuntu/Mint/Pop!_OS (apt), Fedora (dnf), Arch/Manjaro
(pacman). x86_64. Run as your normal user, not root — it asks for sudo when a
section needs it.

Environment overrides: DIY_NODE_MAJOR (default 24), DIY_SITE (default
https://install.vibedout.app), DIY_SKIP_VOICE / DIY_SKIP_AUTOMATION /
DIY_SKIP_GRAFT=1 (passed through to the app's tool installer), DIY_TOOLS_TARBALL +
DIY_APP_VERSION (a local agent-tools tarball and the app version it belongs to),
DIY_SKIP_AGENTD=1 (no diy-agentd user service; DIY_AGENTS_ROOT, DIY_API_PORT and
DIY_AGENTD_PORT, when set, go into its unit), DIY_SKIP_CELLD=1 (no celld, esbuild and weed;
DIY_CELLD_ATTEST=require makes the attestation check mandatory), DIY_SKIP_WHISPERKEY=1 (no
WhisperKey), DIY_WHISPERKEY=1 (install it even where no desktop is found),
DIY_WHISPERKEY_MODEL=0 (leave the speech model to WhisperKey's first start), DIY_GPU_DRIVER=install|skip|ask (the GPU
section's question; ask = the default, which needs a terminal and otherwise does not install).
USAGE
}

# ── arguments ──

CHECK=0
ONLY=""
SKIP=""
WITH=""
while [ $# -gt 0 ]; do
  case "$1" in
    --check) CHECK=1 ;;
    --only) ONLY="${2:?--only needs a list}"; shift ;;
    --only=*) ONLY="${1#*=}" ;;
    --skip) SKIP="${2:?--skip needs a list}"; shift ;;
    --skip=*) SKIP="${1#*=}" ;;
    --agents) AGENTS="${2:?--agents needs a list}"; shift ;;
    --agents=*) AGENTS="${1#*=}" ;;
    --with) WITH="${2:?--with needs a list}"; shift ;;
    --with=*) WITH="${1#*=}" ;;
    --build-machine) WITH="${WITH:+$WITH,}worker" ;;
    -h|--help) usage; exit 0 ;;
    *) say "unknown option: $1 (try --help)" >&2; exit 2 ;;
  esac
  shift
done

csv_has() { case ",$1," in *",$2,"*) return 0 ;; *) return 1 ;; esac; }
for s in ${ONLY//,/ } ${SKIP//,/ } ${WITH//,/ }; do
  case " $ALL_SECTIONS $OPTIONAL_SECTIONS " in *" $s "*) ;; *) say "unknown section: $s (sections: $ALL_SECTIONS $OPTIONAL_SECTIONS)" >&2; exit 2 ;; esac
done
want() {
  if [ -n "$ONLY" ]; then csv_has "$ONLY" "$1"; return; fi
  csv_has "$SKIP" "$1" && return 1
  case " $OPTIONAL_SECTIONS " in *" $1 "*) csv_has "$WITH" "$1"; return ;; esac
  return 0
}

# ── the machine ──

if [ "$(id -u)" -eq 0 ]; then
  say "Run this as your normal user, not root: everything but the system packages installs into your home directory, and it asks for sudo itself." >&2
  exit 1
fi
[ "$(uname -s)" = Linux ] || { say "This script is for Linux." >&2; exit 1; }
ARCH=$(uname -m)
[ "$ARCH" = x86_64 ] || say "${Y}note:${N} DIY Platform is built for x86_64; on $ARCH the app section will be skipped."

. "${DIY_OS_RELEASE:-/etc/os-release}" 2>/dev/null || true
if [ -n "${DIY_PM:-}" ]; then PM=$DIY_PM   # a test, or a machine with two package managers, names the one to use
elif command -v apt-get >/dev/null 2>&1; then PM=apt
elif command -v dnf >/dev/null 2>&1; then PM=dnf
elif command -v pacman >/dev/null 2>&1; then PM=pacman
else PM=none
fi
# An image-based system (DIY OS, Silverblue, Bluefin …): /usr is read-only and
# system packages come with the image, so the package-manager steps step aside.
IMAGE_OS=0; [ -e "${DIY_OSTREE_BOOTED:-/run/ostree-booted}" ] && IMAGE_OS=1

# $USER is a login shell's: a service, cron or `docker exec` does not have it.
USER=${USER:-$(id -un)}

have() { command -v "$1" >/dev/null 2>&1; }
ver()  { "$@" 2>/dev/null | head -1 | tr -s ' ' | cut -c1-60; }

# Everything user-level lands in ~/.local/bin, ~/.cargo/bin, ~/.bun/bin or the
# nvm Node — put them all on PATH for the rest of this run, whether or not the
# shell that started it had them.
export PATH="$HOME/.local/bin:$HOME/.cargo/bin:$HOME/.bun/bin:$PATH"
NVM_DIR="${NVM_DIR:-${XDG_CONFIG_HOME:+$XDG_CONFIG_HOME/nvm}}"
NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
export NVM_DIR
load_nvm() { [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" >/dev/null 2>&1 && nvm use --silent default >/dev/null 2>&1; return 0; }
load_nvm

SUDO=sudo
SUDO_WHY=""
# Can sudo be had? Says why not in SUDO_WHY and fails nothing: a step with a fallback (WhisperKey's AppImage) asks this.
sudo_try() {
  [ "$CHECK" -eq 1 ] && { SUDO_WHY="--check does not use sudo"; return 1; }
  [ "$IMAGE_OS" -eq 1 ] && { SUDO_WHY="image-based OS: that belongs in the image (its Containerfile), not a package install here"; return 1; }
  [ "${SUDO_READY:-0}" -eq 1 ] && return 0
  have sudo || { SUDO_WHY="sudo is not installed — the system section needs it"; return 1; }
  # Under `curl | bash` stdin is the script, so sudo must ask on the terminal
  # (when there is one — in a container or CI there is not, and sudo -n decides).
  if sudo -n true 2>/dev/null; then :
  elif (exec </dev/tty) 2>/dev/null; then sudo -v </dev/tty || { SUDO_WHY="could not get sudo"; return 1; }
  else SUDO_WHY="sudo needs a password and there is no terminal to ask on"; return 1
  fi
  SUDO_READY=1
  # Keep the ticket fresh: the Node and Rust sections take long enough for it
  # to expire before Docker asks again, and a run should not stall on a prompt.
  ( while kill -0 $$ 2>/dev/null; do sudo -n true; sleep 50; done ) >/dev/null 2>&1 &
}
sudo_ok() { sudo_try && return 0; [ "$CHECK" -eq 1 ] || fail "$SUDO_WHY"; return 1; }

# Downloads a URL to a file, quietly, failing on HTTP errors.
fetch() { curl -fsSL --retry 3 --proto '=https' --tlsv1.2 -o "$2" "$1"; }
# The latest release tag of a GitHub project, read from where /releases/latest redirects to: the API allows 60 requests an hour per address,
# which a shared network (or a few runs of this script) uses up, and a vendor installer that asks it for "latest" then fails.
gh_latest_tag() { curl -fsSIL --retry 2 --proto '=https' --tlsv1.2 -o /dev/null -w '%{url_effective}' "https://github.com/$1/releases/latest" 2>/dev/null | sed -n 's|.*/releases/tag/||p'; }
# Runs a vendor's own installer script (rustup, nvm, Claude Code …) with bash.
run_installer() { local url=$1; shift; curl -fsSL --retry 3 --proto '=https' --tlsv1.2 "$url" | bash -s -- "$@"; }

# A line in ~/.profile and ~/.bashrc so new terminals find ~/.local/bin too.
ensure_path_line() {
  local line='case ":$PATH:" in *":$HOME/.local/bin:"*) ;; *) export PATH="$HOME/.local/bin:$PATH" ;; esac  # diy-setup'
  for rc in "$HOME/.profile" "$HOME/.bashrc"; do
    [ -f "$rc" ] || [ "$rc" = "$HOME/.profile" ] || continue
    grep -qF '# diy-setup' "$rc" 2>/dev/null || printf '\n%s\n' "$line" >> "$rc"
  done
}

say "${B}DIY Platform setup${N} ${D}· ${PRETTY_NAME:-Linux} · $PM · $ARCH${N}"
[ "$CHECK" -eq 1 ] && say "${D}--check: reporting only, nothing will be installed${N}"

# ── system ──

APT_PKGS=(build-essential pkg-config git curl wget file ca-certificates gnupg unzip zip xz-utils jq
  libssl-dev libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev librsvg2-dev libxdo-dev patchelf
  cmake clang libclang-dev python3 python3-venv python3-pip
  alsa-utils pulseaudio-utils espeak-ng ffmpeg xdg-utils libsecret-1-0 gnome-keyring
  mesa-vulkan-drivers vulkan-tools)
DNF_PKGS=(gcc gcc-c++ make pkgconf-pkg-config git curl wget file ca-certificates gnupg2 unzip zip xz jq
  openssl-devel webkit2gtk4.1-devel gtk3-devel libappindicator-gtk3-devel librsvg2-devel libxdo-devel patchelf
  cmake clang clang-devel python3 python3-pip
  alsa-utils pulseaudio-utils espeak-ng ffmpeg-free xdg-utils libsecret gnome-keyring fuse-libs
  mesa-vulkan-drivers vulkan-tools)
PACMAN_PKGS=(base-devel git curl wget file ca-certificates gnupg unzip zip xz jq
  openssl webkit2gtk-4.1 gtk3 libayatana-appindicator librsvg xdotool patchelf
  cmake clang python python-pip
  alsa-utils libpulse espeak-ng ffmpeg xdg-utils libsecret gnome-keyring fuse2
  vulkan-tools vulkan-icd-loader vulkan-mesa-layers)

missing_in() { # missing_in <package>… → the ones this machine does not have
  local p
  case $PM in
    apt) for p in "$@"; do dpkg-query -W -f='${Status}' "$p" 2>/dev/null | grep -q 'ok installed' || printf '%s\n' "$p"; done ;;
    dnf) for p in "$@"; do rpm -q "$p" >/dev/null 2>&1 || rpm -q --whatprovides "$p" >/dev/null 2>&1 || printf '%s\n' "$p"; done ;;
    pacman) for p in "$@"; do pacman -Qq "$p" >/dev/null 2>&1 || pacman -Qqg "$p" >/dev/null 2>&1 || printf '%s\n' "$p"; done ;;
  esac
}
missing_system() {
  case $PM in
    apt) missing_in "${APT_PKGS[@]}" ;;
    dnf) missing_in "${DNF_PKGS[@]}" ;;
    pacman) missing_in "${PACMAN_PKGS[@]}" ;;
  esac
}

section_system() {
  head_ "system packages"
  if [ "$IMAGE_OS" -eq 1 ]; then ok "image-based OS — system packages come with the image"; return; fi
  if [ "$PM" = none ]; then fail "no apt, dnf or pacman found — install the build tools, WebKitGTK 4.1 and Python 3 yourself"; return; fi
  local miss; miss=$(missing_system | tr '\n' ' ')
  if [ -z "${miss// }" ]; then ok "all present"; return; fi
  todo "missing: $miss"
  [ "$CHECK" -eq 1 ] && { MISSING+=("system packages: $miss"); return; }
  sudo_ok || return
  case $PM in
    apt)
      $SUDO apt-get update -qq >/dev/null
      # libfuse2 lets an AppImage run; Ubuntu 24.04+ renamed it libfuse2t64.
      local fuse=libfuse2; apt-cache show libfuse2t64 >/dev/null 2>&1 && fuse=libfuse2t64
      # shellcheck disable=SC2086
      $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq $miss $fuse >/dev/null || fail "apt-get install failed" ;;
    dnf)
      # shellcheck disable=SC2086
      $SUDO dnf install -y -q $miss >/dev/null || fail "dnf install failed" ;;
    pacman)
      # shellcheck disable=SC2086
      $SUDO pacman -S --needed --noconfirm $miss || fail "pacman -S failed" ;;
  esac
  [ -z "$(missing_system)" ] && ok "system packages installed"
}

# ── gpu ──
#
# The question this answers is not "is there a driver" but "is the GPU actually used": a kernel driver bound to the card AND a real (not CPU) Vulkan
# device for it. WhisperKey ran for months on the CPU of a machine whose NVIDIA driver had never been installed, and nothing said so.

SYSFS="${DIY_SETUP_SYSFS:-/sys}"

# One line per display controller: "slot vendor device driver" (hex without 0x; driver "-" = none bound).
pci_gpus() {
  local d cls v dev drv
  for d in "$SYSFS"/bus/pci/devices/*; do
    [ -r "$d/class" ] || continue
    cls=$(cat "$d/class" 2>/dev/null)
    case $cls in 0x0300*|0x0302*|0x0380*) ;; *) continue ;; esac
    v=$(cat "$d/vendor" 2>/dev/null); dev=$(cat "$d/device" 2>/dev/null)
    drv=""; [ -L "$d/driver" ] && drv=$(basename "$(readlink "$d/driver")")
    printf '%s %s %s %s\n' "${d##*/}" "${v#0x}" "${dev#0x}" "${drv:--}"
  done
}

# A name for the card: lspci's, else the vendor and the id.
gpu_name() { # gpu_name SLOT VENDOR DEVICE
  local n=""
  have lspci && n=$(lspci -s "$1" -mm 2>/dev/null | awk -F'"' 'NR == 1 { print $4 " " $6 }')
  if [ -z "${n// }" ]; then
    case $2 in 10de) n="NVIDIA graphics device $3" ;; 1002|1022) n="AMD graphics device $3" ;; 8086) n="Intel graphics device $3" ;; *) n="graphics device $2:$3" ;; esac
  fi
  printf '%s' "$n"
}

# NVIDIA's driver branch for a card, from the chip's code name in its name ("GA104 [GeForce RTX 3070]"): current (Turing and later), 580xx
# (Maxwell, Pascal, Volta), 470xx (Kepler), 390xx (Fermi). RPM Fusion and Ubuntu name their packages by it.
nvidia_branch() {
  local chip; chip=$(printf '%s' "$1" | grep -oE '\b(TU|GA|AD|GB|GM|GP|GV|GK|GF)[0-9]+[A-Z]?\b' | head -1)
  case $chip in
    TU*|GA*|AD*|GB*) echo current ;; GM*|GP*|GV*) echo 580xx ;; GK*) echo 470xx ;; GF*) echo 390xx ;;
    *) case $1 in *"RTX 20"*|*"RTX 30"*|*"RTX 40"*|*"RTX 50"*|*"GTX 16"*) echo current ;; *"GTX 10"*|*"GTX 9"*|*"GTX 75"*) echo 580xx ;; *) echo current ;; esac ;;
  esac
}

# Does vulkaninfo list a real (not CPU) device of this vendor? 0 yes, 1 no, 2 vulkaninfo is not installed.
vulkan_has_gpu() { # vulkan_has_gpu VENDOR_HEX
  have vulkaninfo || return 2
  vulkaninfo --summary 2>/dev/null | awk -v want="0x$1" '
    tolower($1) == "vendorid" { v = tolower($3) }
    tolower($1) == "devicetype" { t = tolower($3) }
    tolower($1) == "devicename" { if (v == want && t !~ /cpu/) found = 1 }
    END { exit found ? 0 : 1 }'
}

# Does vulkaninfo list ANY real (not CPU) device? 0 yes, 1 no, 2 vulkaninfo is not installed. (A virtual adapter with virgl or Venus reaches the host's GPU: Vulkan decides.)
vulkan_any_gpu() {
  have vulkaninfo || return 2
  vulkaninfo --summary 2>/dev/null | awk '
    tolower($1) == "devicetype" { t = tolower($3) }
    tolower($1) == "devicename" { if (t !~ /cpu/) found = 1 }
    END { exit found ? 0 : 1 }'
}

secure_boot_on() {
  # The firmware's own variable first (4 bytes of attributes, then 1 = on): no tool needed. mokutil when the variable is not readable.
  local f seen=0
  for f in "$SYSFS"/firmware/efi/efivars/SecureBoot-*; do
    [ -r "$f" ] || continue
    seen=1
    [ "$(od -An -tu1 -j4 -N1 "$f" 2>/dev/null | tr -d ' ')" = 1 ] && return 0
  done
  [ "$seen" -eq 1 ] && return 1
  have mokutil && mokutil --sb-state 2>/dev/null | grep -qi 'enabled'
}

# A yes/no question on the terminal. DIY_GPU_DRIVER=install|skip answers it; with no terminal (CI, a container) the answer is no.
ask_yes() {
  case "${DIY_GPU_DRIVER:-ask}" in install|yes) return 0 ;; skip|no) return 1 ;; esac
  (exec </dev/tty) 2>/dev/null || return 1
  local a; printf '  %s [y/N] ' "$1" >/dev/tty; read -r a </dev/tty || return 1
  case $a in y|Y|yes|YES) return 0 ;; *) return 1 ;; esac
}

gpu_nvidia() { # gpu_nvidia NAME DRIVER
  local name=$1 drv=$2 branch; branch=$(nvidia_branch "$name")
  if [ "$drv" = nvidia ]; then
    if have nvidia-smi && nvidia-smi -L >/dev/null 2>&1; then
      ok "$name — NVIDIA driver $(nvidia-smi --query-gpu=driver_version --format=csv,noheader 2>/dev/null | head -1) is in use"
    else
      todo "$name — NVIDIA's kernel module is bound but nvidia-smi does not answer"
      NOTES+=("The NVIDIA GPU is NOT being used: its driver is installed but does not answer. A restart usually fixes a fresh install; with Secure Boot on, the driver is refused until its key is enrolled at the blue screen after the restart. Check: nvidia-smi.")
      MISSING+=("a working NVIDIA driver for $name")
    fi
    return
  fi
  local now="the kernel driver ${drv/#-/none}"; [ "$drv" = nouveau ] && now="the open nouveau driver"; [ "$drv" = - ] && now="no driver at all"
  todo "$name — running on $now, NOT on NVIDIA's own driver"
  NOTES+=("The NVIDIA GPU ($name) is NOT being used by NVIDIA's driver: it runs on $now. WhisperKey, vibedout Terminal and everything else that could use the GPU runs on the CPU or on the slower open driver.")
  MISSING+=("NVIDIA driver for $name")
  [ "$CHECK" -eq 1 ] && return
  if [ "$IMAGE_OS" -eq 1 ]; then
    NOTES+=("This image carries the open drivers only; the image with NVIDIA's driver is a separate one (50.21-D05).")
    return
  fi
  local sb="" sbon=0; secure_boot_on && sbon=1
  if [ "$sbon" = 1 ]; then
    case $PM in
      apt) sb=" Secure Boot is on: Ubuntu's installer asks you to choose a password, and the next start shows a blue screen (Enroll MOK) where you enter it; without that the driver does not load." ;;
      dnf) sb=" Secure Boot is on: the driver's module must be signed with a key you make and enrol BEFORE the driver is installed (the commands are in that order); without that it does not load." ;;
      *)   sb=" Secure Boot is on: the driver's module must be signed with a key you enrol; without that it does not load." ;;
    esac
  fi
  case $PM in
    apt)
      if have ubuntu-drivers; then
        local rec; rec=$(ubuntu-drivers devices 2>/dev/null | grep -m1 'recommended' | awk '{print $3}')
        say "    ubuntu-drivers recommends: ${rec:-(nothing found: it will say so)}"
        if ask_yes "Install the recommended NVIDIA driver now (sudo ubuntu-drivers install; needs a restart)?"; then
          # (not from the script's own standard input: under `curl | bash` that is the rest of the script, and a password or a question would eat it)
          local tty_in=/dev/null; (exec </dev/tty) 2>/dev/null && tty_in=/dev/tty
          if sudo_ok; then
            if $SUDO ubuntu-drivers install <"$tty_in"; then
              ok "NVIDIA driver installed — restart this machine to use the GPU.$sb"
              NOTES+=("Restart this machine: the NVIDIA driver is installed and only loads at the next start.$sb")
            else fail "ubuntu-drivers install failed"; fi
          fi
        else NOTES+=("To use the GPU: sudo ubuntu-drivers install, then restart.$sb"); fi
      else NOTES+=("Debian and its relatives: enable the non-free component and install the nvidia-driver package, then restart.$sb"); fi ;;
    dnf)
      # RPM Fusion's packages of the card's branch: a legacy branch has its OWN user-space (xorg-x11-drv-nvidia-580xx), the current one has none to add
      local akmod=akmod-nvidia user=xorg-x11-drv-nvidia
      [ "$branch" != current ] && { akmod=akmod-nvidia-$branch; user=xorg-x11-drv-nvidia-$branch; }
      local repos="sudo dnf install https://mirrors.rpmfusion.org/free/fedora/rpmfusion-free-release-\$(rpm -E %fedora).noarch.rpm https://mirrors.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-\$(rpm -E %fedora).noarch.rpm"
      if [ "$sbon" = 1 ]; then
        NOTES+=("To use the GPU (RPM Fusion; not run for you: the module is built on this machine and signed with a key you enrol): $repos && sudo dnf install akmods kmodtool mokutil openssl && sudo kmodgenca -a && sudo mokutil --import /etc/pki/akmods/certs/public_key.der — restart, choose Enroll MOK in the blue screen and type the password; then: sudo dnf install $akmod $user — wait for the module to build (modinfo -F version nvidia), then restart.$sb")
      else
        NOTES+=("To use the GPU (RPM Fusion; not run for you: the module is built on this machine and needs a restart): $repos && sudo dnf install $akmod $user — wait for the module to build (modinfo -F version nvidia), then restart.")
      fi ;;
    pacman)
      local pkg=nvidia-open; [ "$branch" != current ] && pkg="nvidia-$branch-dkms (from the AUR)"
      NOTES+=("To use the GPU: sudo pacman -S $pkg nvidia-utils, then restart. The 580xx, 470xx and 390xx cards need the AUR; Secure Boot needs the module signed by hand.$sb") ;;
    *) NOTES+=("Install your distribution's NVIDIA driver and restart to use the GPU.") ;;
  esac
}

gpu_mesa() { # gpu_mesa LABEL VENDOR NAME DRIVER
  local label=$1 vendor=$2 name=$3 drv=$4 rc
  vulkan_has_gpu "$vendor"; rc=$?
  case $rc in
    0) ok "$name — in use (kernel driver $drv, a real Vulkan device)" ;;
    2) ok "$name — kernel driver $drv; vulkan-tools is not installed, so whether programs get the GPU is not checked (the system section adds it)" ;;
    *)
      todo "$name — the GPU is NOT being used: no Vulkan driver for it"
      NOTES+=("The $label GPU ($name) is NOT being used: the kernel driver ($drv) is loaded but Vulkan lists no device for it, so WhisperKey, vibedout Terminal and the rest run on the CPU. Install Mesa's Vulkan driver (mesa-vulkan-drivers; the system section does) and check with: vulkaninfo --summary")
      MISSING+=("a Vulkan driver for $name") ;;
  esac
}

section_gpu() {
  head_ "graphics (GPU)"
  local lines; lines=$(pci_gpus)
  if [ -z "$lines" ]; then ok "no graphics device found (a server, or a virtual machine without one): everything that draws runs on the CPU"; return; fi
  local slot v dev drv name
  while read -r slot v dev drv; do
    [ -n "$slot" ] || continue
    name=$(gpu_name "$slot" "$v" "$dev")
    case $v in
      1af4|1234|15ad|80ee|1414|1b36|1013)
        if vulkan_any_gpu; then ok "$name — a virtual adapter with a real GPU behind it: Vulkan lists one, so programs that use it get it"
        else ok "$name — a virtual adapter: there is no GPU behind it, so drawing and speech recognition run on the CPU (normal in a virtual machine)"; fi ;;
      1a03|102b|1039|126f)
        ok "$name — a basic display adapter (a server's management graphics): nothing to compute on, everything runs on the CPU, which is what this machine is for" ;;
      10de) gpu_nvidia "$name" "$drv" ;;
      1002|1022) gpu_mesa AMD "$v" "$name" "$drv" ;;
      8086) gpu_mesa Intel "$v" "$name" "$drv" ;;
      *) todo "$name — a graphics device from a vendor this script does not know; whether it is used is not checked" ;;
    esac
  done <<< "$lines"
}

# ── session ──
#
# User-level, no sudo. For GNOME's launcher (the scope it makes is called app-gnome-DIY\x20Platform-<pid>.scope; another desktop names it differently and gets no drop-in
# that does anything). systemd's default for the scope a program is started in from its desktop launcher is OOMPolicy=stop: the kernel ending ONE
# process in it (a build, a test worker, the phone) stops the whole scope, DIY Platform and every terminal and agent in it (seen 4 times in 12 hours,
# 2026-10-19). A drop-in for that scope's name makes it "continue". It does not mark the scope for systemd-oomd (ManagedOOMPreference=avoid): on Fedora 44
# that mark on a cgroup in app.slice sends uresourced and systemd --user into a loop at 100 % of a CPU (found 2026-10-25, 50.21-D06). DIY OS ships the same drop-in.

section_session() {
  head_ "session"
  have systemctl || { ok "no systemd here — nothing to set"; return; }
  [ "$IMAGE_OS" -eq 1 ] && { ok "image-based OS — the image carries it"; return; }
  local dir="$HOME/.config/systemd/user/app-gnome-DIY\\x20Platform-.scope.d" file
  file="$dir/10-diy-oom.conf"
  # a file of an earlier version of this script carried ManagedOOMPreference=avoid, which loops Fedora 44's uresourced: it is written again without it
  if [ -f "$file" ] && grep -q '^OOMPolicy=continue' "$file" && ! grep -q '^ManagedOOMPreference' "$file"; then ok "DIY Platform's launcher scope keeps running when one program is killed"
  elif [ "$CHECK" -eq 1 ]; then todo "a killed program closes all of DIY Platform (the launcher's scope stops as a whole)"; MISSING+=("OOM drop-in for DIY's launcher scope")
  else
    mkdir -p "$dir" && cat > "$file" <<'EOF'
# Made by diy-setup.sh. DIY Platform started from its launcher runs in a scope called app-gnome-DIY\x20Platform-<pid>.scope. systemd's default for a scope is
# OOMPolicy=stop: the kernel ending ONE program in it (a build, a test worker, the phone) stops the whole scope, DIY and every terminal with it.
# continue = only that program goes. No ManagedOOMPreference=avoid on purpose: on Fedora 44 it makes uresourced and systemd --user loop at 100 % of a CPU.
# Delete this folder to undo.
[Scope]
OOMPolicy=continue
EOF
    if [ -f "$file" ]; then ok "DIY Platform's launcher scope will keep running when one program is killed (from the next time it is started from the launcher)"
    else fail "could not write $file"; fi
  fi
  local desktop="${XDG_CURRENT_DESKTOP:-}"
  if [ "$desktop" != "${desktop/GNOME/}" ] && have gsettings; then
    local ms; ms=$(gsettings get org.gnome.mutter check-alive-timeout 2>/dev/null | awk '{print $NF}')
    if [ -n "$ms" ] && [ "$ms" -lt 30000 ] 2>/dev/null; then
      NOTES+=("GNOME offers \"Force Quit / Wait\" after $((ms / 1000)) s of a window not answering — a busy machine or a virtual machine stalls DIY's window for longer than that. To wait a minute: gsettings set org.gnome.mutter check-alive-timeout 60000 (Settings → System check in DIY Platform does the same).")
    fi
  fi
}

# ── node ──

# Is the Node on PATH at least <major>.<minor>?
node_at_least() {
  have node || return 1
  node -e 'const [a, b] = process.versions.node.split(".").map(Number); const [fa, fb] = process.argv.slice(1).map(Number);
    process.exit(a > fa || (a === fa && b >= fb) ? 0 : 1)' "$1" "$2" 2>/dev/null
}
# Is it new enough for what this script installs? Never older than 22.19, which diy-agentd needs (it runs TypeScript with Node's own type
# stripping and uses node:sqlite) and pi needs too; and at least DIY_NODE_MAJOR (24 by default), which n8n 2.x refuses to run below.
node_ok() {
  if [ "$NODE_MAJOR" -le 22 ] 2>/dev/null; then node_at_least 22 19; else node_at_least "$NODE_MAJOR" 0; fi
}

# Global npm installs must not need sudo. A system Node owns /usr/lib; point
# its global prefix at ~/.local instead (nvm's Node is already user-owned).
fix_npm_prefix() {
  have npm || return 0
  local prefix; prefix=$(npm config get prefix 2>/dev/null)
  if [ -n "$prefix" ] && [ ! -w "$prefix/lib" ] && [ ! -w "$prefix" ]; then
    npm config set prefix "$HOME/.local" && ok "npm global prefix → ~/.local (no sudo for -g)"
  fi
}

npm_global() { # npm_global <bin> <package> <label>
  local bin=$1 pkg=$2 label=$3
  if have "$bin"; then ok "$label $(ver "$bin" --version)"; return; fi
  todo "$label ($pkg)"
  [ "$CHECK" -eq 1 ] && { MISSING+=("$label"); return; }
  have npm || { fail "$label: npm is missing (node section)"; return; }
  npm install -g --silent --no-fund --no-audit "$pkg" >/dev/null 2>&1 && have "$bin" && ok "$label $(ver "$bin" --version)" || fail "$label: npm install -g $pkg failed"
}

section_node() {
  head_ "node"
  if node_ok; then ok "node $(node -v)"
  else
    todo "node $NODE_MAJOR via nvm (have: $(have node && node -v || echo none))"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("node >= $NODE_MAJOR")
    else
      if [ ! -s "$NVM_DIR/nvm.sh" ]; then
        local tag; tag=$(gh_latest_tag nvm-sh/nvm)
        PROFILE=/dev/null run_installer "https://raw.githubusercontent.com/nvm-sh/nvm/${tag:-v0.40.8}/install.sh" >/dev/null 2>&1 || fail "nvm install failed"
        # The installer only edits rc files when PROFILE is real; add the loader ourselves, once.
        grep -qF 'nvm.sh' "$HOME/.bashrc" 2>/dev/null || printf '\nexport NVM_DIR="%s"\n[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"\n' "$NVM_DIR" >> "$HOME/.bashrc"
      fi
      load_nvm
      if have nvm || [ -s "$NVM_DIR/nvm.sh" ]; then
        . "$NVM_DIR/nvm.sh" && nvm install "$NODE_MAJOR" >/dev/null 2>&1 && nvm alias default "$NODE_MAJOR" >/dev/null && nvm use default >/dev/null \
          && ok "node $(node -v) (nvm)" || fail "nvm install $NODE_MAJOR failed"
      fi
    fi
  fi
  [ "$CHECK" -eq 1 ] || fix_npm_prefix
  npm_global pnpm pnpm@10 pnpm
  if have bun; then ok "bun $(ver bun --version)"
  else
    todo "bun"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("bun")
    elif ! have unzip; then fail "bun needs unzip (system section)"
    else run_installer https://bun.sh/install >/dev/null 2>&1 && have bun && ok "bun $(ver bun --version)" || fail "bun install failed"; fi
  fi
}

# ── rust ──

section_rust() {
  head_ "rust"
  if have rustup; then
    ok "rustup $(ver rustup --version | cut -d' ' -f2) · $(ver rustc --version)"
    [ "$CHECK" -eq 1 ] || rustup toolchain list 2>/dev/null | grep -q stable || rustup toolchain install stable --profile default >/dev/null 2>&1
    return
  fi
  if have cargo; then ok "cargo $(ver cargo --version) (not rustup-managed — fine for building, but Android targets need rustup)"; return; fi
  todo "rustup + stable toolchain"
  [ "$CHECK" -eq 1 ] && { MISSING+=("rust"); return; }
  run_installer https://sh.rustup.rs -y --default-toolchain stable --profile default >/dev/null 2>&1 \
    && . "$HOME/.cargo/env" && ok "$(ver rustc --version)" || fail "rustup install failed"
}

# ── python ──

section_python() {
  head_ "python"
  if have python3; then ok "$(ver python3 --version)"; else fail "python3 missing (system section)"; fi
  python3 -c 'import venv, ensurepip' 2>/dev/null && ok "venv + pip" || { todo "python3 venv/pip (system section installs them)"; MISSING+=("python3-venv"); }
  if have uv; then ok "uv $(ver uv --version | cut -d' ' -f2)"
  else
    todo "uv"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("uv")
    else UV_NO_MODIFY_PATH=1 run_installer https://astral.sh/uv/install.sh >/dev/null 2>&1 && have uv && ok "uv $(ver uv --version | cut -d' ' -f2)" || fail "uv install failed"; fi
  fi
}

# ── docker ──

section_docker() {
  head_ "docker"
  if have docker; then
    ok "$(ver docker --version)"
    docker compose version >/dev/null 2>&1 && ok "compose $(docker compose version --short 2>/dev/null)" || { todo "docker compose plugin"; MISSING+=("docker compose"); }
  else
    todo "Docker Engine + compose"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("docker")
    else
      sudo_ok || return
      case $PM in
        pacman) $SUDO pacman -S --needed --noconfirm docker docker-compose docker-buildx || fail "pacman docker failed" ;;
        *)
          # Docker's own script covers Debian, Ubuntu and Fedora. Derivatives it
          # does not recognise (Mint, Pop!_OS …) fall back to the distro packages.
          local tmp="$WORK/get-docker.sh"
          if fetch https://get.docker.com "$tmp" && $SUDO sh "$tmp" >/dev/null 2>&1; then :
          elif [ "$PM" = apt ]; then
            $SUDO apt-get install -y -qq docker.io && { $SUDO apt-get install -y -qq docker-compose-v2 || $SUDO apt-get install -y -qq docker-compose-plugin; } || fail "docker packages failed"
          else
            $SUDO dnf install -y -q moby-engine docker-compose || fail "docker packages failed"
          fi
;;
      esac
      have docker && ok "$(ver docker --version)"
    fi
  fi
  [ "$CHECK" -eq 1 ] && { id -nG | grep -qw docker || MISSING+=("docker group membership"); return; }
  have docker || return
  if have systemctl && ! systemctl is-active --quiet docker 2>/dev/null; then
    sudo_ok && $SUDO systemctl enable --now docker >/dev/null 2>&1 && ok "docker service started"
  fi
  if ! id -nG "$USER" | grep -qw docker; then
    sudo_ok && $SUDO usermod -aG docker "$USER" && { ok "added $USER to the docker group"; NOTES+=("Log out and back in (or run: newgrp docker) so docker works without sudo."); }
  else ok "$USER is in the docker group"
  fi
}

# ── agents ──

# Which coding agents to install. Claude Code, Codex and the Antigravity CLI (agy) are never a choice (DIY OS decision 50.52-D02, the founder, 2026-10-25:
# "Claude is the main agent, even if you don't select anything"; "all these three just install by default and you can expand later on"): every run of the
# section wants them. --agents (or DIY_AGENTS) names the EXTRA agents on top, gemini pi opencode; with neither, the extras are gemini and pi. A list that
# names claude, codex or agy is accepted: they are wanted anyway. Leaving the three out means leaving the whole section out: --skip agents.
CORE_AGENTS="claude codex agy"
EXTRA_AGENTS_DEFAULT="gemini,pi"
want_agent() {
  case " $CORE_AGENTS " in *" $1 "*) return 0 ;; esac
  case ",${AGENTS:-${DIY_AGENTS:-$EXTRA_AGENTS_DEFAULT}}," in *",$1,"*) return 0 ;; esac
  return 1
}

section_agents() {
  head_ "coding agents"
  if have claude; then ok "Claude Code $(ver claude --version)"
  else
    todo "Claude Code"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("Claude Code")
    else run_installer https://claude.ai/install.sh >/dev/null 2>&1 && have claude && ok "Claude Code $(ver claude --version)" || fail "Claude Code install failed"; fi
  fi
  npm_global codex @openai/codex "Codex CLI"
  want_agent gemini && npm_global gemini @google/gemini-cli "Gemini CLI"
  want_agent pi && npm_global pi @earendil-works/pi-coding-agent "pi coding agent"
  want_agent opencode && npm_global opencode opencode-ai "OpenCode"
  if have agy; then ok "Antigravity CLI (agy) $(ver agy --version)"
  else
    todo "Antigravity CLI (agy)"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("Antigravity CLI")
    else run_installer https://antigravity.google/cli/install.sh >/dev/null 2>&1 && have agy && ok "Antigravity CLI (agy) $(ver agy --version)" || fail "Antigravity CLI install failed"; fi
  fi
  # herdr runs agent sessions in panes the app can hand back and forth.
  if have herdr; then ok "$(ver herdr --version)"
  else
    todo "herdr"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("herdr")
    else curl -fsSL https://herdr.dev/install.sh | sh >/dev/null 2>&1 && have herdr && ok "$(ver herdr --version)" || fail "herdr install failed"; fi
  fi
  # The three, then the extras that were asked for (a core agent named again is not listed twice).
  local chosen="claude, codex, agy" x
  for x in $(echo "${AGENTS:-${DIY_AGENTS:-$EXTRA_AGENTS_DEFAULT}}" | tr ',' ' '); do
    case " $CORE_AGENTS " in *" $x "*) ;; *) chosen="$chosen, $x" ;; esac
  done
  NOTES+=("Sign in to each agent once: $chosen.")
}

# ── cli ──

section_cli() {
  head_ "developer CLIs"
  if have gh; then ok "$(ver gh --version)"
  else
    todo "GitHub CLI (gh)"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("gh")
    elif sudo_ok; then
      case $PM in
        apt)
          $SUDO mkdir -p -m 755 /etc/apt/keyrings
          curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | $SUDO tee /etc/apt/keyrings/githubcli-archive-keyring.gpg >/dev/null
          $SUDO chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg
          echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | $SUDO tee /etc/apt/sources.list.d/github-cli.list >/dev/null
          $SUDO apt-get update -qq && $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq gh >/dev/null ;;
        dnf) $SUDO dnf install -y -q gh >/dev/null ;;
        pacman) $SUDO pacman -S --needed --noconfirm github-cli ;;
      esac
      have gh && ok "$(ver gh --version)" || fail "gh install failed"
    fi
  fi
  npm_global wrangler wrangler "wrangler (Cloudflare)"
  if have supabase; then ok "supabase $(ver supabase --version)"
  else
    todo "supabase CLI"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("supabase CLI")
    else
      local tmp="$WORK/supabase"; mkdir -p "$tmp"
      fetch https://github.com/supabase/cli/releases/latest/download/supabase_linux_amd64.tar.gz "$tmp/s.tgz" \
        && tar -xzf "$tmp/s.tgz" -C "$tmp" supabase && install -m755 "$tmp/supabase" "$HOME/.local/bin/supabase" \
        && ok "supabase $(ver supabase --version)" || fail "supabase CLI install failed"
    fi
  fi
  # Agent memory (Hindsight) — the app runs its server in Docker; this is the client.
  if have hindsight; then ok "$(ver hindsight --version)"
  else
    todo "hindsight CLI"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("hindsight CLI")
    else
      # Its installer asks the GitHub API for the latest version unless it is told one.
      HINDSIGHT_CLI_VERSION=$(gh_latest_tag vectorize-io/hindsight) run_installer https://hindsight.vectorize.io/get-cli >/dev/null 2>&1 && have hindsight && ok "$(ver hindsight --version)" || fail "hindsight CLI install failed"
    fi
  fi
  # Hardware projects. Installed into ~/.local/bin, where the app looks first (not the snap).
  if have arduino-cli; then ok "$(ver arduino-cli version)"
  else
    todo "arduino-cli"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("arduino-cli")
    else
      curl -fsSL https://raw.githubusercontent.com/arduino/arduino-cli/master/install.sh | BINDIR="$HOME/.local/bin" sh >/dev/null 2>&1 \
        && have arduino-cli && ok "$(ver arduino-cli version)" || fail "arduino-cli install failed"
    fi
  fi
}

# ── app ──

# Reads one field from the release manifest the site publishes.
manifest_get() { # manifest_get <file> <python expression over `m` and `linux`>
  python3 -I -c 'import json,sys
m=json.load(open(sys.argv[1])); linux=next((p for p in m["platforms"] if p["id"]=="linux"),{"assets":[]})
def asset(suffix):
    a=next((a for a in linux["assets"] if a["file"].endswith(suffix)),None)
    return " ".join([a["url"], a["sha256"], a["file"]]) if a else ""
print(eval(sys.argv[2]))' "$1" "$2"
}

# This script records what it installed; without that record, ask dpkg.
MARKER="$HOME/.local/share/diy-platform/.installed-version"
installed_app_version() {
  if [ -f "$MARKER" ]; then cat "$MARKER"; return; fi
  if have dpkg-query && dpkg-query -W -f='${Version}' diy-platform 2>/dev/null; then return; fi
  # rpm -q says "package … is not installed" on stdout, which is not a version.
  have rpm && rpm -q --quiet diy-platform 2>/dev/null && rpm -q --qf '%{VERSION}' diy-platform 2>/dev/null
}

download_verified() { # download_verified "<url> <sha256> <file>" <dir> → prints the path
  local url sha file; read -r url sha file <<<"$1"
  [ -n "${url:-}" ] || return 1
  fetch "$url" "$2/$file" || { bad "download failed: $url"; return 1; }
  echo "$sha  $2/$file" | sha256sum -c --quiet - >/dev/null 2>&1 || { bad "checksum mismatch: $file"; return 1; }
  printf '%s\n' "$2/$file"
}

# ── the agent service (diy-agentd) ──
#
# diy-agentd is the always-on agent daemon the tools install puts at ~/.local/bin/diy-agentd. On a desktop it runs as a systemd *user*
# service, started now and at every login — what the Agent section's "Install & start" button in DIY Platform does, written the same
# way (the unit is src-tauri/src/agentd_service.rs's, and carries its "Managed by DIY Platform" line, so the app can still rewrite it).
# It is TypeScript that Node strips itself, so it needs Node 22.19 or newer — and the user manager's PATH is not the login shell's:
# the system node is often 18, the nvm one is in no unit's PATH, so the unit puts the folder of the Node found here first.
AGENTD_UNIT=diy-agentd.service
AGENTD_MARK='# Managed by DIY Platform'

# Is there a systemd user manager to talk to? Over ssh or sudo the session variables are missing even though the manager runs.
user_systemd() {
  have systemctl || return 1
  local rt; rt="/run/user/$(id -u)"
  [ -n "${XDG_RUNTIME_DIR:-}" ] || { [ -d "$rt" ] && export XDG_RUNTIME_DIR=$rt; }
  [ -n "${DBUS_SESSION_BUS_ADDRESS:-}" ] || { [ -S "${XDG_RUNTIME_DIR:-$rt}/bus" ] && export DBUS_SESSION_BUS_ADDRESS="unix:path=${XDG_RUNTIME_DIR:-$rt}/bus"; }
  systemctl --user show-environment >/dev/null 2>&1
}

port_ok() { case $1 in ""|*[!0-9]*) return 1 ;; esac; [ "$1" -ge 1 ] && [ "$1" -le 65535 ]; }

# A value for a quoted Environment="K=V" line: \ " and % escaped; refuses a control character.
unit_esc() {
  case $1 in *[[:cntrl:]]*) return 1 ;; esac
  local v=$1; v=${v//\\/\\\\}; v=${v//\"/\\\"}; v=${v//%/%%}; printf '%s' "$v"
}

# The unit, as DIY Platform writes it (agentd_service.rs `unit_text`): the DIY OS one minus Wants=diyd.service, which a desktop has not
# got, with the Node's folder first on the PATH.
agentd_unit_text() { # agentd_unit_text <folder of a Node 22.19+, or empty>
  local path vars e api_port=7421
  port_ok "${DIY_API_PORT:-}" && api_port=$DIY_API_PORT
  path='%h/.local/bin:%h/.cargo/bin:%h/.bun/bin:%h/.local/share/pnpm:/usr/local/bin:/usr/bin'
  if [ -n "$1" ]; then e=$(unit_esc "$1") || return 1; path="$e:$path"; fi
  e=%h/Agents
  if [ -n "${DIY_AGENTS_ROOT:-}" ]; then e=$(unit_esc "$DIY_AGENTS_ROOT") || return 1; fi
  vars="Environment=\"PATH=$path\"
Environment=\"DIY_AGENTS_ROOT=$e\"
Environment=\"DIY_API=http://127.0.0.1:$api_port/api\""
  if port_ok "${DIY_AGENTD_PORT:-}"; then
    vars="$vars
Environment=\"DIY_AGENTD_PORT=$DIY_AGENTD_PORT\""
  fi
  if [ -n "${XDG_CONFIG_HOME:-}" ] && [ "$XDG_CONFIG_HOME" != "$HOME/.config" ]; then
    e=$(unit_esc "$XDG_CONFIG_HOME") || return 1
    vars="$vars
Environment=\"XDG_CONFIG_HOME=$e\""
  fi
  cat <<EOF
[Unit]
Description=DIY Agent (diy-agentd): the agents above every project
$AGENTD_MARK (diy-setup.sh, install.vibedout.app; the Agent section's Start button writes the same). Edit it freely: DIY only rewrites a unit that still has this line.
Documentation=https://install.vibedout.app
ConditionPathExists=%h/.local/bin/diy-agentd
StartLimitIntervalSec=5min
StartLimitBurst=5

[Service]
Type=simple
ExecStart=%h/.local/bin/diy-agentd
# Node 22.19 or newer: the system node is often older, so the one found when this was written comes first.
$vars
Restart=on-failure
RestartSec=5
# 3 = another diy-agentd already holds the agents folder: not a fault that another start would cure.
RestartPreventExitStatus=3
# A tool an agent started dying for lack of memory must not stop the daemon.
OOMPolicy=continue
KillSignal=SIGTERM
TimeoutStopSec=30
LimitNOFILE=65536

[Install]
WantedBy=default.target
EOF
}

# Where the daemon answers: DIY_AGENTD_PORT, else what it wrote when it last started, else 7480.
agentd_port() {
  local p=${DIY_AGENTD_PORT:-} f="${DIY_AGENTS_ROOT:-$HOME/Agents}/.agentd/daemon.json"
  if ! port_ok "$p"; then p=""; [ -f "$f" ] && p=$(sed -n 's/.*"port" *: *\([0-9][0-9]*\).*/\1/p' "$f" | head -1); fi
  port_ok "$p" || p=7480
  printf '%s' "$p"
}

agentd_answers() { curl -fsS --max-time 2 "http://127.0.0.1:$(agentd_port)/health" 2>/dev/null | grep -Eq '"service" *: *"diy-agentd"'; }

# Does the unit's PATH find a Node of 22.19 or newer? (`%h` is the home folder in a unit.) What decides whether a unit this script or the
# app wrote still works: the folder of an nvm Node that was removed leaves the system's, which may be 18.
unit_path_node_ok() { # unit_path_node_ok <unit file>
  local p; p=$(sed -n 's/^Environment="PATH=\(.*\)"$/\1/p' "$1" | head -1)
  [ -n "$p" ] || return 1
  p=${p//%h/$HOME}; p=${p//%%/%}
  PATH="$p" node_at_least 22 19
}

agentd_service() {
  local launcher="$HOME/.local/bin/diy-agentd"
  if [ "${DIY_SKIP_AGENTD:-0}" = 1 ]; then ok "agent service: skipped (DIY_SKIP_AGENTD=1)"; return; fi
  if [ ! -x "$launcher" ]; then
    # Whether the tools installed is said by the step above; this is only what the service needs.
    [ "$CHECK" -eq 1 ] || NOTES+=("There is no diy-agentd in ~/.local/bin (the agent tools of this release lack it, or they did not install), so no agent service was set up.")
    return
  fi
  if ! user_systemd; then
    todo "agent service: no systemd user session here"
    NOTES+=("No systemd user session on this login, so diy-agentd was not set up as a service. Start it from DIY Platform (Agents → Start), or run: diy-agentd")
    return
  fi

  # Whose unit is there? Like the app (agentd_service.rs `install_unit`): none → write one; with the "Managed by DIY Platform" line → ours,
  # kept up to date; any other unit, or a mask → the person's, left as it is; /usr/lib or /etc/systemd/user → the image's (DIY OS).
  local user_unit="$HOME/.config/systemd/user/$AGENTD_UNIT" frag d state=none
  frag=$(systemctl --user show -p FragmentPath --value "$AGENTD_UNIT" 2>/dev/null)
  if [ -L "$user_unit" ] && [ "$(readlink -f "$user_unit")" = /dev/null ]; then state=masked
  elif [ -e "$user_unit" ]; then
    if grep -qF "$AGENTD_MARK" "$user_unit"; then state=managed; else state=own; fi
  elif [ -n "$frag" ]; then
    case $frag in /usr/*|/etc/*|/lib/*) state=image ;; *) state=own ;; esac
  else
    for d in /etc/systemd/user /usr/lib/systemd/user; do [ -f "$d/$AGENTD_UNIT" ] && state=image; done
  fi

  case $state in
    masked)
      ok "agent service: $AGENTD_UNIT is masked — left as it is"; return ;;
    image)
      # DIY OS ships the unit and its roles (diy-os-roles) switch it on for the "agent" use; a profile that left that use out is the person's
      # choice. (A profile with no "uses" at all is the wizard's default, which has the agent use on.)
      local profile="$HOME/.config/diy-os/profile.json"; [ -f "$profile" ] || profile=/etc/diy-os/profile.json
      if [ -f "$profile" ] && have python3 && ! python3 -I -c 'import json,sys; sys.exit(0 if "agent" in json.load(open(sys.argv[1])).get("uses", ["agent"]) else 1)' "$profile" 2>/dev/null; then
        ok "agent service: this DIY OS profile leaves the agent use out — not started"; return
      fi ;;
  esac

  # A unit is written when there is none, or when ours no longer finds a good Node.
  local write=0 want="" node_dir=""
  case $state in
    none) write=1 ;;
    managed) unit_path_node_ok "$user_unit" || write=1 ;;
  esac
  if [ "$write" -eq 1 ]; then
    if node_at_least 22 19; then
      node_dir=$(dirname "$(command -v node)")
      case $node_dir in /usr/bin|/bin|/usr/local/bin) node_dir="" ;; esac
      want=$(agentd_unit_text "$node_dir") || { fail "agent service: could not write the unit (an odd character in a path)"; return; }
    elif [ "$CHECK" -eq 1 ]; then
      todo "agent service (needs a Node of 22.19 or newer)"; MISSING+=("diy-agentd service"); return
    else
      fail "agent service: no Node 22.19 or newer for diy-agentd (node section)"; return
    fi
  fi

  if [ "$CHECK" -eq 1 ]; then
    local active enabled
    active=$(systemctl --user is-active "$AGENTD_UNIT" 2>/dev/null); enabled=$(systemctl --user is-enabled "$AGENTD_UNIT" 2>/dev/null)
    if [ "$write" -eq 0 ] && [ "$active" = active ] && [ "$enabled" = enabled ]; then ok "agent service running, starts at login"
    else todo "agent service (${active:-not set up}, ${enabled:-not enabled})"; MISSING+=("diy-agentd service"); fi
    return
  fi

  local changed=0
  if [ "$write" -eq 1 ]; then
    { mkdir -p "${user_unit%/*}" && printf '%s\n' "$want" > "$user_unit.tmp" && mv "$user_unit.tmp" "$user_unit"; } || { fail "agent service: could not write $user_unit"; return; }
    systemctl --user daemon-reload || { fail "agent service: systemctl --user daemon-reload failed"; return; }
    changed=1
  elif [ "$state" = own ]; then
    NOTES+=("${frag:-$user_unit} is your own unit (it has no \"Managed by DIY Platform\" line), so it was left as it is; its PATH must have a Node 22.19 or newer first.")
  fi
  systemctl --user reset-failed "$AGENTD_UNIT" >/dev/null 2>&1 || true
  systemctl --user enable "$AGENTD_UNIT" >/dev/null 2>&1 || { fail "agent service: systemctl --user enable $AGENTD_UNIT failed (journalctl --user -u diy-agentd)"; return; }
  if [ "$changed" -eq 1 ] && systemctl --user is-active --quiet "$AGENTD_UNIT"; then
    systemctl --user restart "$AGENTD_UNIT" || { fail "agent service: could not restart $AGENTD_UNIT"; return; }
  else
    systemctl --user start "$AGENTD_UNIT" || { fail "agent service: could not start $AGENTD_UNIT (journalctl --user -u diy-agentd)"; return; }
  fi
  local _
  for _ in $(seq 1 30); do
    agentd_answers && break
    systemctl --user is-failed --quiet "$AGENTD_UNIT" && break
    sleep 1
  done
  if agentd_answers; then ok "agent service running on 127.0.0.1:$(agentd_port), starts at login"
  elif [ "$(systemctl --user is-active "$AGENTD_UNIT" 2>/dev/null)" != active ]; then
    fail "agent service is not running: journalctl --user -u diy-agentd (a Node older than 22.19, or port $(agentd_port) taken)"
  else todo "agent service started, but it does not answer yet (journalctl --user -u diy-agentd)"; fi
}

section_app() {
  head_ "DIY Platform"
  [ "$ARCH" = x86_64 ] || { fail "DIY Platform is only built for x86_64"; return; }
  have python3 || { fail "python3 is needed to read the release manifest (system section)"; return; }
  local tmp="$WORK/app"; mkdir -p "$tmp"
  fetch "$SITE/releases/diy-platform.json" "$tmp/release.json" || { fail "could not read $SITE/releases/diy-platform.json"; return; }
  local latest current; latest=$(manifest_get "$tmp/release.json" 'm["version"]'); current=$(installed_app_version)
  # DIY OS images built with an unreleased app bring its agent tools along
  # (DIY_TOOLS_TARBALL + DIY_APP_VERSION): that version is the one to have.
  local local_tools=""
  if [ -n "${DIY_TOOLS_TARBALL:-}" ] && [ -f "$DIY_TOOLS_TARBALL" ] && [ -n "${DIY_APP_VERSION:-}" ]; then
    local_tools=$DIY_TOOLS_TARBALL; latest=$DIY_APP_VERSION
  fi

  if [ "$current" = "$latest" ]; then ok "app $current (latest)"
  else
    todo "app ${current:+$current → }$latest"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("DIY Platform $latest")
    else
      if pgrep -x diy-platform >/dev/null 2>&1; then todo "closing the running DIY Platform so it can be replaced"; pkill -x diy-platform; sleep 1; fi
      local pkg
      if [ "$PM" = apt ] && pkg=$(download_verified "$(manifest_get "$tmp/release.json" 'asset(".deb")')" "$tmp"); then
        if sudo_ok && $SUDO apt-get install -y -qq "$pkg" >/dev/null; then
          mkdir -p "${MARKER%/*}" && echo "$latest" > "$MARKER"
          ok "app $latest (.deb, checksum verified)"
          # An older hand install (the source checkout's install.sh without sudo) would shadow /usr/bin.
          [ -x "$HOME/.local/bin/diy-platform" ] && NOTES+=("~/.local/bin/diy-platform is an older copy that runs instead of the new /usr/bin/diy-platform — delete it.")
        else fail "installing the .deb failed"; fi
      elif [ "$PM" = dnf ] && [ "$IMAGE_OS" -eq 0 ] && pkg=$(download_verified "$(manifest_get "$tmp/release.json" 'asset(".rpm")')" "$tmp"); then
        if sudo_ok && $SUDO dnf install -y -q "$pkg" >/dev/null; then
          mkdir -p "${MARKER%/*}" && echo "$latest" > "$MARKER"
          ok "app $latest (.rpm, checksum verified)"
        else fail "installing the .rpm failed"; fi
      elif [ "$IMAGE_OS" -eq 1 ] && [ -n "$current" ]; then
        NOTES+=("This image has DIY Platform $current; $latest arrives with the next image (diy-os update).")
      elif pkg=$(download_verified "$(manifest_get "$tmp/release.json" 'asset(".AppImage")')" "$tmp"); then
        mkdir -p "$HOME/.local/bin" "$HOME/.local/share/applications" "$HOME/.local/share/diy-platform"
        install -m755 "$pkg" "$HOME/.local/bin/diy-platform" && echo "$latest" > "$MARKER"
        cat > "$HOME/.local/share/applications/diy-platform.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=DIY Platform
Exec=$HOME/.local/bin/diy-platform
Terminal=false
Categories=Development;
EOF
        ok "app $latest (AppImage → ~/.local/bin/diy-platform, checksum verified)"
      else
        fail "no Linux installer could be downloaded and verified"
      fi
    fi
  fi

  # The agent tools — MCP server, `diy` CLI, voice, n8n, graft — are the app's
  # own install.sh (--tools-only), shipped as a tarball next to the installer.
  local tools_ver=""; [ -f "$HOME/.local/share/diy-platform/tools/.version" ] && tools_ver=$(cat "$HOME/.local/share/diy-platform/tools/.version")
  if [ "$tools_ver" = "$latest" ]; then ok "agent tools $latest"
  else
    todo "agent tools (MCP server, diy CLI, voice, n8n, graft)"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("DIY agent tools $latest")
    else
      have pnpm && have node || { fail "agent tools need node and pnpm (node section)"; return; }
      local tgz
      if [ -n "$local_tools" ]; then tgz=$local_tools
      else tgz=$(download_verified "$(manifest_get "$tmp/release.json" 'asset("_linux-tools.tar.gz")')" "$tmp") || { fail "agent tools tarball missing from release $latest"; return; }; fi
      local src="$tmp/diy-platform-$latest"
      if tar -xzf "$tgz" -C "$tmp" && [ -f "$src/install.sh" ] && bash "$src/install.sh" --tools-only; then
        echo "$latest" > "$HOME/.local/share/diy-platform/tools/.version"
        ok "agent tools $latest"
      else fail "agent tools install failed (output above)"; fi
    fi
  fi
  if have claude && claude mcp get diy-platform >/dev/null 2>&1; then ok "MCP server registered with Claude Code"
  elif have claude && [ "$CHECK" -eq 1 ]; then MISSING+=("diy-platform MCP registration"); fi
  agentd_service
}

# ── celld ──
#
# `diy-celld` (50.41-T11) comes with the agent tools of the app section; this fetches the three programs it runs, the pinned ones:
# `diy-celld install` checks each download against the sha256 pinned in its pins.json (and celld's GitHub build attestation when gh is
# there). They go to ~/.local/lib/diy/celld with no root, no Docker and nothing on a port. Nothing is started: the bucket and each app
# are user units that `diy-celld app install` makes, on loopback ports. On DIY OS the image has the binaries and this finds them.
section_celld() {
  head_ "celld (Workers projects on this machine, no Cloudflare account)"
  if [ "${DIY_SKIP_CELLD:-0}" = 1 ]; then ok "skipped (DIY_SKIP_CELLD=1)"; return; fi
  case "$ARCH" in x86_64|aarch64) ;; *) ok "skipped — celld, esbuild and weed are pinned for x86_64 and aarch64 only"; return ;; esac
  local tool="" c
  for c in "$HOME/.local/bin/diy-celld" "$(command -v diy-celld 2>/dev/null)"; do
    if [ -n "$c" ] && [ -x "$c" ]; then tool=$c; break; fi
  done
  if [ -z "$tool" ]; then
    # Releases before the one that carries it have no diy-celld in their agent tools: not a failure of this machine.
    [ "$CHECK" -eq 1 ] || NOTES+=("There is no diy-celld in ~/.local/bin (the agent tools of this release lack it), so celld, esbuild and weed were not installed. They come with the next DIY Platform release.")
    ok "diy-celld is not part of these agent tools yet"
    return
  fi
  have node || { fail "diy-celld needs node (node section)"; return; }
  if [ "$CHECK" -eq 1 ]; then
    if "$tool" install --check >/dev/null 2>&1; then ok "celld, esbuild and weed are installed, the pinned versions"
    else todo "celld, esbuild and weed (missing, or not the pinned versions)"; MISSING+=("celld, esbuild and weed"); fi
    return
  fi
  local out
  if out=$("$tool" install --attest "${DIY_CELLD_ATTEST:-auto}" 2>&1); then
    printf '%s\n' "$out" | grep -E '^(installed|kept) ' | while IFS= read -r line; do ok "$line"; done
  else
    printf '%s\n' "$out" | tail -5 | while IFS= read -r line; do bad "$line"; done
    fail "diy-celld install failed (output above)"
    return
  fi
  NOTES+=("Run a Workers project on this machine: diy-celld app install <project-folder>  (opens at http://127.0.0.1:<port>; diy-celld doctor checks it).")
}

# ── whisperkey ──
#
# WhisperKey (apps/whisperkey) is vibedout's own offline dictation: press Ctrl+Space in any application, speak, press it again, and the
# transcript is pasted where the cursor is. Its releases are published beside DIY Platform's, with the same manifest shape
# ($SITE/releases/whisperkey.json) — a .deb, an AppImage and, when one is built, an .rpm. Its own installer (install-linux.sh) installs the
# package, turns "start with the computer" on and downloads the speech model; this does the same from the published release.

# The version this script recorded for a WhisperKey it installed (an AppImage has no package database), and, from a new install until its
# first-time setup (start with the session, the speech model) has gone through, a second file: a run that could not finish the setup
# finishes it next time, and no other run ever does it (someone who turned the login entry off in Settings keeps it off).
WK_MARKER="$HOME/.local/share/diy-platform/.whisperkey-version"
WK_PENDING="$HOME/.local/share/diy-platform/.whisperkey-setup-pending"

has_display() { [ -n "${DISPLAY:-}${WAYLAND_DISPLAY:-}" ]; }
# A machine somebody sits at: a display in this session, or a system that boots to the graphical target (a script run over ssh has no DISPLAY).
has_desktop() { has_display || [ "$(systemctl get-default 2>/dev/null)" = graphical.target ]; }

# a < b as versions.
ver_lt() { [ "$1" != "$2" ] && [ "$(printf '%s\n%s\n' "$1" "$2" | sort -V | head -1)" = "$1" ]; }

# The WhisperKey in use: on PATH, in /usr/bin (the .deb or .rpm) or in ~/.local/bin (the AppImage this script installs).
wk_bin() {
  local c
  for c in "$(command -v whisperkey 2>/dev/null)" /usr/bin/whisperkey "$HOME/.local/bin/whisperkey"; do
    if [ -n "$c" ] && [ -x "$c" ]; then printf '%s\n' "$c"; return 0; fi
  done
  return 1
}

# Its version, when a package manager or this script knows it (`whisperkey --version` is not a thing: any other argument starts the app).
# The launcher this script puts in ~/.local/bin comes first on PATH, so when that is what runs its record wins over an older package's.
wk_version() {
  local v=""
  if [ -f "$WK_MARKER" ] && [ "$(wk_bin 2>/dev/null)" = "$HOME/.local/bin/whisperkey" ]; then v=$(cat "$WK_MARKER"); fi
  if [ -z "$v" ] && have dpkg-query && dpkg-query -W -f='${Status}' whisper-key 2>/dev/null | grep -q 'ok installed'; then v=$(dpkg-query -W -f='${Version}' whisper-key 2>/dev/null); fi
  if [ -z "$v" ] && have rpm && [ -x /usr/bin/whisperkey ]; then v=$(rpm -qf --qf '%{VERSION}' /usr/bin/whisperkey 2>/dev/null) || v=""; fi
  if [ -z "$v" ] && [ -f "$WK_MARKER" ]; then v=$(cat "$WK_MARKER"); fi
  printf '%s' "$v"
}

# The AppImage is unpacked, not kept as a file: an AppImage needs FUSE 2 to start (libfuse2 / fuse-libs, which an image-based system or a
# minimal one has not got), and the unpacked copy starts faster. ~/.local/bin/whisperkey is a launcher for it, and — like an AppImage's
# own path — what WhisperKey's login entry is made to start.
WK_APP="$HOME/.local/share/whisperkey/app"
wk_unpack_appimage() { # wk_unpack_appimage <the .AppImage>
  local img=$1 bin="$HOME/.local/bin/whisperkey" tmp="${WK_APP%/*}/.unpack"
  # Unpacked beside its destination, so the last step is a rename on one filesystem.
  rm -rf "$tmp"; mkdir -p "$tmp" "$HOME/.local/bin" "$HOME/.local/share/applications" "$HOME/.local/share/icons"
  chmod +x "$img"
  ( cd "$tmp" && "$img" --appimage-extract >/dev/null 2>&1 </dev/null ) && [ -x "$tmp/squashfs-root/AppRun" ] || { rm -rf "$tmp"; return 1; }
  rm -rf "$WK_APP.old"; [ -e "$WK_APP" ] && mv "$WK_APP" "$WK_APP.old"
  mv "$tmp/squashfs-root" "$WK_APP" || return 1
  rm -rf "$WK_APP.old" "$tmp"
  printf '#!/bin/sh\n# WhisperKey, unpacked from its AppImage by diy-setup.sh (no FUSE needed).\nexec "%s/AppRun" "$@"\n' "$WK_APP" > "$bin.new" \
    && chmod 755 "$bin.new" && mv -f "$bin.new" "$bin" || return 1
  cp -r "$WK_APP/usr/share/icons/." "$HOME/.local/share/icons/" 2>/dev/null || true
  cat > "$HOME/.local/share/applications/whisperkey.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=WhisperKey
Comment=Offline system-wide dictation
Exec=$bin
Icon=whisperkey
Terminal=false
Categories=Utility;AudioVideo;
EOF
  update-desktop-database "$HOME/.local/share/applications" 2>/dev/null || true
}

# Close the running WhisperKey that is the one about to be replaced — the installed binary or the unpacked app — and no other process of
# that name (a build from a checkout, an AppImage somebody runs from Downloads). A running copy holds the control port and the GNOME hotkey;
# replacing the binary under it leaves one answering with old code. Says 0 when it closed one.
wk_stop_ours() { # wk_stop_ours <the whisperkey in use>
  local want pid exe stopped=1
  want=$(readlink -f "$1" 2>/dev/null)
  for pid in $(pgrep -x whisperkey 2>/dev/null); do
    exe=$(readlink -f "/proc/$pid/exe" 2>/dev/null)
    case $exe in
      "$want"|"$WK_APP"/*) todo "closing the running WhisperKey ($pid) so it can be replaced"; kill "$pid" 2>/dev/null && stopped=0 ;;
    esac
  done
  [ "$stopped" -eq 0 ] && sleep 1
  return "$stopped"
}

# Start WhisperKey for this session. From a systemd service (DIY OS runs this at first login as a oneshot unit) a plain background process
# is in the service's cgroup and ends with it, so it is started as a transient user unit of its own.
wk_start() { # wk_start <whisperkey>
  if [ -n "${INVOCATION_ID:-}" ] && have systemd-run && user_systemd; then
    systemd-run --user --collect -q --unit="whisperkey-setup-$$" ${DISPLAY:+--setenv=DISPLAY="$DISPLAY"} ${WAYLAND_DISPLAY:+--setenv=WAYLAND_DISPLAY="$WAYLAND_DISPLAY"} \
      ${XAUTHORITY:+--setenv=XAUTHORITY="$XAUTHORITY"} "$1" >/dev/null 2>&1 </dev/null
  else
    ( setsid "$1" >/dev/null 2>&1 </dev/null & )
  fi
}

# What a new install gets: the same switch as Settings → "Start with the computer", so the two cannot disagree, and the speech model.
wk_first_setup() { # wk_first_setup <whisperkey>
  local bin=$1 err
  # APPIMAGE is how an AppImage tells WhisperKey the path to start at login; here that is the launcher.
  if err=$(APPIMAGE="$bin" "$bin" --autostart on 2>&1 </dev/null); then
    ok "WhisperKey starts with your session (Settings → Start with the computer)"
    rm -f "$WK_PENDING"
  else
    fail "WhisperKey: could not turn on start-with-the-computer ($bin --autostart on): $(printf '%s' "$err" | tail -1 | cut -c1-160)"; return 1
  fi
  if [ "${DIY_WHISPERKEY_MODEL:-1}" = 0 ]; then
    NOTES+=("WhisperKey downloads its speech model (488 MB) the first time it starts.")
  else
    todo "downloading WhisperKey's speech model (488 MB, once)"
    if timeout 1500 "$bin" --setup-stt --with-model >/dev/null 2>&1 </dev/null; then ok "speech model ready"
    else NOTES+=("WhisperKey's speech model did not finish downloading (see ~/.local/share/whisperkey/setup.log); it tries again each time WhisperKey starts.")
    fi
  fi
}

section_whisperkey() {
  head_ "WhisperKey (dictation in any application)"
  if [ "${DIY_SKIP_WHISPERKEY:-0}" = 1 ]; then ok "skipped (DIY_SKIP_WHISPERKEY=1)"; return; fi
  [ "$ARCH" = x86_64 ] || { ok "skipped — WhisperKey is only built for x86_64"; return; }
  # Dictation is for a machine with a screen. Asking for the section by name (--only), or DIY_WHISPERKEY=1, installs it anyway.
  if [ -z "$ONLY" ] && [ "${DIY_WHISPERKEY:-0}" != 1 ] && ! has_desktop; then
    ok "skipped — no desktop session on this machine (DIY_WHISPERKEY=1 or --only whisperkey installs it anyway)"; return
  fi
  have python3 || { fail "python3 is needed to read the release manifest (system section)"; return; }
  local tmp="$WORK/whisperkey"; mkdir -p "$tmp"
  fetch "$SITE/releases/whisperkey.json" "$tmp/release.json" || { fail "could not read $SITE/releases/whisperkey.json"; return; }
  local latest bin cur
  latest=$(manifest_get "$tmp/release.json" 'm["version"]'); bin=$(wk_bin || true); cur=$(wk_version)
  [ -n "$latest" ] || { fail "$SITE/releases/whisperkey.json has no version"; return; }

  local upgrade=0
  if [ -n "$bin" ] && [ -z "$cur" ]; then ok "WhisperKey is installed ($bin, not by this script) — left as it is"; return
  elif [ -n "$bin" ] && ! ver_lt "$cur" "$latest"; then
    ok "WhisperKey $cur$([ "$cur" = "$latest" ] && echo ' (latest)')"
    if [ -f "$WK_PENDING" ]; then
      if [ "$CHECK" -eq 1 ]; then todo "WhisperKey: the first-time setup (start with the session) did not finish"; MISSING+=("WhisperKey setup"); else wk_first_setup "$bin"; fi
    fi
    return
  elif [ -n "$bin" ]; then upgrade=1; todo "WhisperKey $cur → $latest"
  else todo "WhisperKey $latest (not installed)"
  fi
  if [ "$CHECK" -eq 1 ]; then MISSING+=("WhisperKey $latest"); return; fi

  # The distro's package when the release has one for it (apt: .deb, dnf: .rpm), else the AppImage, unpacked under ~/.local/share/whisperkey.
  # Everything is downloaded and checked before the running copy is closed.
  local how="" pkg suffix was_running=0 pkgurl
  if [ "$IMAGE_OS" -eq 0 ] && { [ "$PM" = apt ] || [ "$PM" = dnf ]; }; then
    suffix=.deb; [ "$PM" = dnf ] && suffix=.rpm
    pkgurl=$(manifest_get "$tmp/release.json" "asset(\"$suffix\")")
    if [ -z "$pkgurl" ]; then :   # this release has no package for the distro
    elif ! sudo_try; then todo "$SUDO_WHY — using the AppImage instead"
    elif pkg=$(download_verified "$pkgurl" "$tmp"); then
      if [ "$upgrade" -eq 1 ] && wk_stop_ours "$bin"; then was_running=1; fi
      if [ "$PM" = apt ]; then $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq "$pkg" >/dev/null && how="$suffix package"
      else $SUDO dnf install -y -q "$pkg" >/dev/null && how="$suffix package"; fi
      [ -n "$how" ] || bad "the WhisperKey $suffix did not install — using the AppImage instead"
    fi
  fi
  if [ -z "$how" ]; then
    if pkg=$(download_verified "$(manifest_get "$tmp/release.json" 'asset(".AppImage")')" "$tmp"); then
      if [ "$upgrade" -eq 1 ] && wk_stop_ours "$bin"; then was_running=1; fi
      if wk_unpack_appimage "$pkg"; then how="AppImage, unpacked in ~/.local/share/whisperkey"; else bad "could not unpack the WhisperKey AppImage"; fi
    fi
  fi
  [ -n "$how" ] || { fail "WhisperKey: no Linux installer could be downloaded and installed"; return; }
  mkdir -p "${WK_MARKER%/*}" && echo "$latest" > "$WK_MARKER"
  if [ "$upgrade" -eq 0 ]; then : > "$WK_PENDING"; fi
  bin=$(wk_bin) || { fail "WhisperKey installed, but no whisperkey is on the PATH"; return; }
  ok "WhisperKey $latest ($how, checksum verified)"

  local setup_ok=1
  if [ "$upgrade" -eq 0 ]; then wk_first_setup "$bin" || setup_ok=0; fi

  # Start it for this session when there is one: its first start also puts the Ctrl+Space hotkey in on GNOME.
  if [ "$setup_ok" -eq 0 ]; then :
  elif { [ "$was_running" -eq 1 ] || [ "$upgrade" -eq 0 ]; } && has_display && ! pgrep -x whisperkey >/dev/null 2>&1; then
    wk_start "$bin"
    sleep 4
    if pgrep -x whisperkey >/dev/null 2>&1; then ok "WhisperKey started — click the widget or press Ctrl+Space to dictate"
    else NOTES+=("WhisperKey did not start from here; run whisperkey in a terminal to see why. It also starts from your next login.")
    fi
  else
    NOTES+=("Start WhisperKey with: whisperkey — it starts by itself from your next login. Press Ctrl+Space, speak, press it again.")
  fi
  # README: Hyprland, Sway and KDE on Wayland refuse an application's global hotkey (GNOME and X11 get one).
  case "${XDG_CURRENT_DESKTOP:-}:${XDG_SESSION_TYPE:-}" in
    *GNOME*:*|*:x11|*:|*:tty) ;;
    *) NOTES+=("WhisperKey: ${XDG_CURRENT_DESKTOP:-this desktop} on Wayland may not let an application register a hotkey — if Ctrl+Space does nothing, bind a key in your desktop's settings to: whisperkey --toggle") ;;
  esac
}

# ── android (optional) ──

# The JDK on PATH, when it is 17 or 21 (the LTS releases Gradle and the Android plugin work with).
jdk_ok() { have javac && javac -version 2>&1 | grep -Eq ' (17|21)\.'; }

section_android() {
  head_ "android"
  if jdk_ok; then ok "$(javac -version 2>&1)"
  else
    todo "JDK 17 (or 21)"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("JDK 17 (or 21)")
    elif sudo_ok; then
      # Not every release still packages 17: Debian 13 has 21 only, Fedora 44 only 25 (too new for the Android plugin).
      case $PM in
        apt) $SUDO apt-get install -y -qq openjdk-17-jdk >/dev/null 2>&1 || $SUDO apt-get install -y -qq openjdk-21-jdk >/dev/null 2>&1 ;;
        dnf) $SUDO dnf install -y -q java-17-openjdk-devel >/dev/null 2>&1 || $SUDO dnf install -y -q java-21-openjdk-devel >/dev/null 2>&1 ;;
        pacman) $SUDO pacman -S --needed --noconfirm jdk17-openjdk >/dev/null 2>&1 || $SUDO pacman -S --needed --noconfirm jdk21-openjdk >/dev/null 2>&1 ;;
      esac
      if jdk_ok; then ok "$(javac -version 2>&1)"
      else NOTES+=("No JDK 17 or 21 could be installed from this distribution's packages; DIY Platform downloads its own portable JDK 17 (Mobile → Set up), which is all a build from the app needs.")
      fi
    fi
  fi
  if have rustup; then
    local t; for t in aarch64-linux-android armv7-linux-androideabi x86_64-linux-android i686-linux-android; do
      if rustup target list --installed 2>/dev/null | grep -qx "$t"; then ok "rust target $t"
      elif [ "$CHECK" -eq 1 ]; then MISSING+=("rust target $t")
      else rustup target add "$t" >/dev/null 2>&1 && ok "rust target $t" || fail "rustup target add $t"; fi
    done
  else fail "rustup is needed for the Android targets (rust section)"; fi
  NOTES+=("The Android SDK, NDK and emulator image are installed by DIY Platform itself (Mobile → Set up), into a folder it manages.")
}

# ── flutter (optional) ──

# The SDK is a git checkout of Flutter's stable branch (what flutter.dev recommends): `flutter upgrade` moves it on, and its first run
# fetches the Dart SDK and the engine with their own checksums.
FLUTTER_DIR="$HOME/.local/share/flutter"

section_flutter() {
  head_ "flutter"
  # What Flutter's Linux desktop target adds to the system section (clang, cmake, pkg-config and GTK are there already).
  local pk="" miss=""
  case $PM in apt) pk="ninja-build liblzma-dev" ;; dnf) pk="ninja-build xz-devel" ;; pacman) pk="ninja xz" ;; esac
  # shellcheck disable=SC2086
  [ -n "$pk" ] && miss=$(missing_in $pk | tr '\n' ' ')
  if [ -z "${miss// }" ]; then ok "Linux desktop build packages"
  else
    todo "Linux desktop build packages: $miss"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("flutter build packages: $miss")
    elif sudo_ok; then
      # shellcheck disable=SC2086
      case $PM in
        apt) $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq $miss >/dev/null 2>&1 || { $SUDO apt-get update -qq && $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq $miss >/dev/null; } ;;
        dnf) $SUDO dnf install -y -q $miss >/dev/null ;;
        pacman) $SUDO pacman -S --needed --noconfirm $miss >/dev/null ;;
      esac || fail "flutter build packages failed to install"
    fi
  fi
  if have flutter; then ok "$(ver flutter --version | cut -d' ' -f1-2)"
  else
    todo "Flutter SDK (stable)"
    if [ "$CHECK" -eq 1 ]; then MISSING+=("flutter")
    elif ! have git; then fail "flutter needs git (system section)"
    else
      mkdir -p "$HOME/.local/bin"
      if [ ! -x "$FLUTTER_DIR/bin/flutter" ]; then
        [ -e "$FLUTTER_DIR" ] && { fail "flutter: $FLUTTER_DIR exists and is not a Flutter checkout — move it away and run again"; return; }
        # Cloned beside its destination and renamed into place, so an interrupted clone leaves nothing that looks like an SDK.
        rm -rf "$FLUTTER_DIR.new"
        GIT_TERMINAL_PROMPT=0 git clone --depth 1 -b stable https://github.com/flutter/flutter.git "$FLUTTER_DIR.new" >/dev/null 2>&1 </dev/null \
          && mv "$FLUTTER_DIR.new" "$FLUTTER_DIR" || { rm -rf "$FLUTTER_DIR.new"; fail "flutter: git clone of the stable branch failed"; return; }
      fi
      # A link of the person's own (a standalone Dart, say) is left alone.
      local t
      for t in flutter dart; do
        if [ ! -e "$HOME/.local/bin/$t" ] && [ ! -L "$HOME/.local/bin/$t" ] || [ "$(readlink "$HOME/.local/bin/$t")" = "$FLUTTER_DIR/bin/$t" ]; then ln -sf "$FLUTTER_DIR/bin/$t" "$HOME/.local/bin/$t"
        else NOTES+=("$HOME/.local/bin/$t exists and is not Flutter's, so it was left as it is; Flutter's is $FLUTTER_DIR/bin/$t.")
        fi
      done
      if timeout 1500 "$FLUTTER_DIR/bin/flutter" --version >/dev/null 2>&1 </dev/null; then ok "$(ver flutter --version | cut -d' ' -f1-2) → $FLUTTER_DIR"
      else fail "flutter: the first run (it fetches the Dart SDK) failed — run flutter --version to see why"; fi
    fi
  fi
  NOTES+=("Run flutter doctor once: it lists what is left for Android and the Linux desktop target.")
}

# ── images (optional) ──

# What the app starts on demand, as it pins them (src-tauri/src/services/*.yaml, provision.rs). Convex has no pin: its images are `latest`.
IMAGES=(pgvector/pgvector:pg16
  ghcr.io/vectorize-io/hindsight:0.9.2-slim@sha256:97ab9978ddf1394fc6a163f4c779fa9c7e5123770c881844bd2e0e9a60b0d18a
  public.ecr.aws/supabase/postgres-meta:v0.98.0 public.ecr.aws/supabase/studio:2026.08.17-sha-0c1da8f
  ghcr.io/get-convex/convex-backend:latest ghcr.io/get-convex/convex-dashboard:latest)

section_images() {
  head_ "docker images"
  have docker || { fail "docker is not installed (docker section)"; return; }
  local d="docker"; docker info >/dev/null 2>&1 || { [ "$CHECK" -eq 1 ] || d="sudo docker"; }
  local img; for img in "${IMAGES[@]}"; do
    if $d image inspect "$img" >/dev/null 2>&1; then ok "$img"
    elif [ "$CHECK" -eq 1 ]; then MISSING+=("image $img")
    else todo "pulling $img"; $d pull -q "$img" >/dev/null && ok "$img" || fail "docker pull $img"; fi
  done
}

# ── worker (optional, --build-machine; 51.40-T27) ──

# The build machine script of the app's own release when its tools are installed (it then matches the app), else the site's.
section_worker() {
  head_ "build machine"
  case $PM in apt|dnf) ;; *) fail "a build machine is Ubuntu, Debian or Fedora (setup-linux.sh knows apt and dnf): not set up here"; return ;; esac
  local f="$HOME/.local/share/diy-platform/tools/worker/setup-linux.sh"
  if [ ! -f "$f" ]; then
    f="$WORK/setup-linux.sh"
    fetch "$SITE/worker/setup-linux.sh" "$f" || { fail "could not download $SITE/worker/setup-linux.sh"; return; }
  fi
  if [ "$CHECK" -eq 1 ]; then
    if id diy-worker >/dev/null 2>&1; then ok "the diy-worker user is there"; NOTES+=("What the build machine has, part by part: sudo bash $f --check")
    else todo "build machine"; MISSING+=("build machine (--build-machine)"); fi
    return
  fi
  sudo_ok || return
  if $SUDO bash "$f" </dev/null; then
    ok "build machine"
    NOTES+=("To send DIY's lane jobs to this build machine, join it to your DIY: on your DIY's computer run  diy worker add <this machine's address>, then here  curl -fsSL $SITE/worker/setup-linux.sh | sudo bash -s -- --join")
  else
    fail "the build machine set-up (setup-linux.sh) stopped: the lines above say why"
  fi
}

# ── run ──

NOTES=()
WORK=$(mktemp -d); trap 'rm -rf "$WORK"' EXIT
[ "$CHECK" -eq 1 ] || { mkdir -p "$HOME/.local/bin"; ensure_path_line; }
for s in $ALL_SECTIONS $OPTIONAL_SECTIONS; do
  want "$s" && "section_$s"
done

head_ "summary"
if [ "$CHECK" -eq 1 ]; then
  if [ ${#MISSING[@]} -eq 0 ]; then ok "nothing missing"; else for m in "${MISSING[@]}"; do todo "$m"; done; say "  Run without --check to install them."; fi
fi
if [ ${#FAILED[@]} -gt 0 ]; then
  for f in "${FAILED[@]}"; do bad "$f"; done
  say "  Fix the cause and run the script again — finished steps are skipped."
fi
for n in "${NOTES[@]}"; do say "  ${Y}•${N} $n"; done
if [ "$CHECK" -eq 0 ] && [ ${#FAILED[@]} -eq 0 ]; then
  ok "done. Open a new terminal (so PATH and nvm load), then start DIY Platform from your app menu or with: diy-platform"
fi
[ ${#FAILED[@]} -eq 0 ]
}

main "$@" --end-of-script
