#!/usr/bin/env bash
#
# setup-user-tools.sh - rootless installer for terminal tools.
#
# Usage:
#   setup-user-tools.sh [--all] [--only LIST] [--skip-brew] [--no-dotfiles]
#                       [--dry-run] [--list] [--force] [--text-menu] [-h|--help]
#
#   --all            install everything, no menu
#   --only fd,rg,nvim  install just these ids (see --list)
#   --skip-brew      never install Homebrew; skip brew-only items
#   --no-dotfiles    do not offer the dotfiles step
#   --dry-run        print the plan and change nothing
#   --list           print the catalogue and stop
#   --force          reinstall items that look present
#   --text-menu      use the plain line menu instead of the full-screen picker
#
# One-liner:
#   url=https://nithitsuki.com/scripts/setup-user-tools.sh; if command -v curl >/dev/null; then curl -fsSL "$url" | bash; else wget -qO- "$url" | bash; fi
#
# Guarantees: runs as your normal user and never uses sudo. It never calls a
# system package manager (pacman, apt, dnf, zypper, apk). Binaries go to
# ~/.local/bin, trees to ~/.local/opt, and Homebrew to ~/.linuxbrew only.
#
# Side effects: writes a marker-guarded PATH block into ~/.profile,
# ~/.bashrc and ~/.zshrc (existing symlinks are skipped, never written
# through), and at the end offers to clone
# https://github.com/nithitsuki/dotfiles and run its run.sh. Homebrew may
# create ~/.cache for its downloads.
#
set -euo pipefail

BIN_DIR="$HOME/.local/bin"
OPT_DIR="$HOME/.local/opt"
BREW="$HOME/.linuxbrew"
GH="https://github.com"
OPENCODE_BASE="https://opencode.ai/update/api/latest/cli/opencode"
MARK_BEGIN="# >>> nithitsuki tools >>>"
TRIPLE=""

TOOL_IDS=(
  fd rg nvim fastfetch fzf bat eza zoxide btop jq tldr starship tetris opencode
  emacs zsh vim htop tmux git stow
  lsd lf yt-dlp lazygit gh yazi dysk
  trash-cli ffmpeg mpv rsync gnupg chafa
  zsh-autosuggestions zsh-syntax-highlighting zsh-completions zsh-autocomplete
)

TOOL_GROUPS=(
  "Core CLI"
  "Editors and shell"
  "Dotfiles helpers"
  "Git and media"
  "Files and disks"
  "Zsh plugins"
)

ALL=0 ONLY="" FORCE=0 LIST=0 DRY_RUN=0 SKIP_BREW=0 NO_DOTFILES=0
TEXT_MENU=0
INTERACTIVE=0
TTY_FD=0
ASK_REPLY=""
BREW_FAILED=0
WORKDIR=""
TUI_ACTIVE=0
TUI_ROWS=24
TUI_COLS=80
TUI_TOP=0
TUI_CUR=0
TUI_BUF=""
TUI_TEXT=""
TUI_KEY=""
TUI_TTY_STATE=""
TUI_RESIZED=0
TUI_KIND=()
TUI_ID=()
INSTALLED=() PRESENT=() SKIPPED=() FAILED=()
NOTES=()
declare -A SELECTED=()

# ---------------------------------------------------------------- utilities

die() {
  printf 'error: %s\n' "$*" >&2
  exit 1
}

note() { printf '  %s\n' "$*"; }

warn() { printf 'warning: %s\n' "$*" >&2; }

# When the script arrives through `curl | bash`, stdin carries the script, so
# prompts need the controlling terminal. Open it once on fd 3; never replace
# stdin, because bash is still reading the script from it.
setup_tty() {
  if [[ -t 0 ]]; then
    INTERACTIVE=1
    return 0
  fi
  if [[ -r /dev/tty ]] && { exec 3</dev/tty; } 2>/dev/null; then
    TTY_FD=3
    INTERACTIVE=1
  fi
}

# ask [prompt] -> sets ASK_REPLY; returns 1 on EOF.
ask() {
  local prompt=${1:-}
  if [[ -n $prompt ]]; then
    printf '%s' "$prompt"
  fi
  if [[ $TTY_FD == 3 ]]; then
    if ! read -r -u 3 ASK_REPLY; then
      ASK_REPLY=""
      return 1
    fi
  else
    if ! read -r ASK_REPLY; then
      ASK_REPLY=""
      return 1
    fi
  fi
  return 0
}

# shellcheck disable=SC2317 # only invoked through the EXIT trap
cleanup() {
  tui_restore
  if [[ -n $WORKDIR && -d $WORKDIR ]]; then
    rm -rf "$WORKDIR"
  fi
}
trap cleanup EXIT

ensure_workdir() {
  if [[ -z $WORKDIR ]]; then
    WORKDIR=$(mktemp -d "${TMPDIR:-/tmp}/setup-user-tools.XXXXXX")
  fi
}

join_list() {
  if (($# == 0)); then
    printf -- '-'
    return 0
  fi
  printf '%s' "$1"
  shift
  local item
  for item in "$@"; do
    printf ' %s' "$item"
  done
}

# ---------------------------------------------------------------- catalogue

tool_bin() {
  case $1 in
    tetris) printf 'tetris-cli' ;;
    trash-cli) printf 'trash-put' ;;
    zsh-autosuggestions | zsh-syntax-highlighting | zsh-completions | zsh-autocomplete) printf '' ;;
    *) printf '%s' "$1" ;;
  esac
}

tool_method() {
  case $1 in
    emacs | zsh | vim | htop | tmux | git | stow | \
      trash-cli | ffmpeg | mpv | rsync | gnupg | chafa | \
      zsh-autosuggestions | zsh-syntax-highlighting | zsh-completions | zsh-autocomplete)
      printf 'brew'
      ;;
    *) printf 'portable' ;;
  esac
}

tool_group() {
  case $1 in
    nvim | vim | emacs | zsh) printf 'Editors and shell' ;;
    git | stow | rsync | gnupg) printf 'Dotfiles helpers' ;;
    lazygit | gh | yt-dlp | ffmpeg | mpv | chafa) printf 'Git and media' ;;
    lsd | lf | yazi | dysk | trash-cli | zoxide) printf 'Files and disks' ;;
    zsh-autosuggestions | zsh-syntax-highlighting | zsh-completions | zsh-autocomplete)
      printf 'Zsh plugins'
      ;;
    *) printf 'Core CLI' ;;
  esac
}

tool_desc() {
  case $1 in
    fd) printf 'Fast find alternative' ;;
    rg) printf 'Fast recursive grep' ;;
    bat) printf 'cat with syntax highlighting' ;;
    eza) printf 'Modern ls replacement' ;;
    fzf) printf 'Fuzzy finder' ;;
    jq) printf 'JSON processor' ;;
    tldr) printf 'Simplified man pages' ;;
    starship) printf 'Cross-shell prompt' ;;
    fastfetch) printf 'System information display' ;;
    btop) printf 'System monitor' ;;
    htop) printf 'Interactive process viewer' ;;
    tmux) printf 'Terminal multiplexer' ;;
    opencode) printf 'Terminal AI coding agent' ;;
    tetris) printf 'Tetris in the terminal' ;;
    nvim) printf 'Neovim editor' ;;
    vim) printf 'Vi IMproved' ;;
    emacs) printf 'GNU Emacs' ;;
    zsh) printf 'Z shell' ;;
    git) printf 'Version control' ;;
    stow) printf 'Symlink farm manager for dotfiles' ;;
    rsync) printf 'Fast file copy and sync' ;;
    gnupg) printf 'GPG signing and encryption' ;;
    lazygit) printf 'Terminal UI for git' ;;
    gh) printf 'GitHub CLI' ;;
    yt-dlp) printf 'Video downloader' ;;
    ffmpeg) printf 'Audio and video converter' ;;
    mpv) printf 'Media player' ;;
    chafa) printf 'Terminal image viewer' ;;
    lsd) printf 'LSDeluxe ls replacement' ;;
    lf) printf 'Terminal file manager' ;;
    yazi) printf 'Fast terminal file manager' ;;
    dysk) printf 'Disk usage viewer' ;;
    trash-cli) printf 'Move files to the trash' ;;
    zsh-autosuggestions) printf 'Fish-style zsh suggestions' ;;
    zsh-syntax-highlighting) printf 'Fish-style zsh highlighting' ;;
    zsh-completions) printf 'Extra zsh completion definitions' ;;
    zsh-autocomplete) printf 'Real-time zsh completions' ;;
    zoxide) printf 'Smarter cd command' ;;
    *) printf '%s' "$1" ;;
  esac
}

# Defaults for the interactive menu.
tool_default() {
  case $1 in
    eza | zoxide | btop | tldr | emacs | tmux | stow | \
      mpv | rsync | gnupg | yazi | dysk | chafa | \
      zsh-autosuggestions | zsh-syntax-highlighting | zsh-completions | zsh-autocomplete)
      printf '0'
      ;;
    *) printf '1' ;;
  esac
}

tool_exists() {
  local id
  for id in "${TOOL_IDS[@]}"; do
    [[ $id == "$1" ]] && return 0
  done
  return 1
}

tool_present() {
  local id=$1 bin
  bin=$(tool_bin "$id")
  if [[ -n $bin ]]; then
    if command -v "$bin" >/dev/null 2>&1; then
      return 0
    fi
    if [[ -x "$BIN_DIR/$bin" ]]; then
      return 0
    fi
  fi
  if [[ $(tool_method "$id") == brew ]]; then
    if [[ -n $bin && -x "$BREW/bin/$bin" ]]; then
      return 0
    fi
    # Formula-only items (zsh plugins) have no binary to look for.
    if [[ -d "$BREW/Cellar/$id" ]]; then
      return 0
    fi
  fi
  return 1
}

# ---------------------------------------------------------------- selection

select_all() {
  local id
  for id in "${TOOL_IDS[@]}"; do
    SELECTED[$id]=1
  done
}

select_none() {
  local id
  for id in "${TOOL_IDS[@]}"; do
    SELECTED[$id]=0
  done
}

select_defaults() {
  local id
  for id in "${TOOL_IDS[@]}"; do
    SELECTED[$id]=$(tool_default "$id")
  done
}

select_only() {
  local list=$1 item
  local -a items
  select_none
  IFS=',' read -r -a items <<<"$list"
  for item in "${items[@]}"; do
    item=${item//[[:space:]]/}
    [[ -z $item ]] && continue
    if ! tool_exists "$item"; then
      die "unknown tool in --only: $item (run --list for ids)"
    fi
    SELECTED[$item]=1
  done
}

selected_count() {
  local id count=0
  for id in "${TOOL_IDS[@]}"; do
    if [[ ${SELECTED[$id]:-0} == 1 ]]; then
      count=$((count + 1))
    fi
  done
  printf '%s' "$count"
}

any_selected() {
  (($(selected_count) > 0))
}

has_brew_selection() {
  local id
  for id in "${TOOL_IDS[@]}"; do
    if [[ ${SELECTED[$id]:-0} == 1 && $(tool_method "$id") == brew ]]; then
      return 0
    fi
  done
  return 1
}

# ---------------------------------------------------------------- downloads

download() { # url destination
  local url=$1 out=$2
  if command -v curl >/dev/null 2>&1; then
    curl -fL --proto '=https' --proto-redir '=https' \
      --retry 2 --connect-timeout 20 -sS -o "$out" "$url"
  elif command -v wget >/dev/null 2>&1; then
    wget -q -O "$out" "$url"
  else
    warn "neither curl nor wget is available"
    return 1
  fi
}

verify_sha256() { # file checksum-url
  local file=$1 url=$2 expected actual
  if ! command -v sha256sum >/dev/null 2>&1; then
    warn "sha256sum is required to verify $file"
    return 1
  fi
  if ! download "$url" "$file.sha256"; then
    warn "could not download checksum $url"
    return 1
  fi
  expected=$(awk 'NR == 1 {print $1}' "$file.sha256")
  actual=$(sha256sum "$file" | awk '{print $1}')
  if [[ -z $expected || $expected != "$actual" ]]; then
    warn "sha256 mismatch for $file (expected ${expected:-none}, got $actual)"
    return 1
  fi
}

# Extract only if no entry escapes the destination directory.
extract_tar() { # archive destination
  local archive=$1 dest=$2
  if tar -tzf "$archive" | grep -Eq '(^/|(^|/)\.\.(/|$))'; then
    warn "refusing archive with unsafe paths: $archive"
    return 1
  fi
  mkdir -p "$dest"
  tar -xzf "$archive" -C "$dest" --no-same-owner
}

zip_entries() { # archive
  if command -v unzip >/dev/null 2>&1; then
    unzip -Z1 "$1"
  else
    python3 - "$1" <<'PY'
import sys, zipfile
with zipfile.ZipFile(sys.argv[1]) as archive:
    for name in archive.namelist():
        print(name)
PY
  fi
}

# Zip needs unzip, or python3 as a fallback. Both paths get the safety check.
extract_zip() { # archive destination
  local archive=$1 dest=$2 entries
  if ! command -v unzip >/dev/null 2>&1 && ! command -v python3 >/dev/null 2>&1; then
    warn "unzip or python3 is required to extract $archive"
    return 1
  fi
  if ! entries=$(zip_entries "$archive"); then
    warn "could not list $archive"
    return 1
  fi
  if grep -Eq '(^/|(^|/)\.\.(/|$))' <<<"$entries"; then
    warn "refusing archive with unsafe paths: $archive"
    return 1
  fi
  mkdir -p "$dest"
  if command -v unzip >/dev/null 2>&1; then
    unzip -q "$archive" -d "$dest"
  else
    python3 -m zipfile -e "$archive" "$dest"
  fi
}

find_bin() { # dir name
  local dir=$1 name=$2 found
  found=$(find "$dir" -type f -name "$name" -print -quit 2>/dev/null)
  if [[ -z $found ]]; then
    return 1
  fi
  printf '%s' "$found"
}

# ------------------------------------------------------- portable installer

portable_record() { # id -> url|sha|kind|binary|dest
  local id=$1 musl nvim_arch fzf_arch ff_arch jq_arch tldr_arch eza_asset oc_arch
  local lf_arch ytdlp_asset lazygit_arch gh_arch
  musl="${TRIPLE}-unknown-linux-musl"

  case $TRIPLE in
    x86_64)
      nvim_arch=x86_64 fzf_arch=amd64 ff_arch=amd64 jq_arch=amd64
      tldr_arch=x86_64 oc_arch=x64
      lf_arch=amd64 ytdlp_asset=yt-dlp_linux lazygit_arch=x86_64 gh_arch=amd64
      eza_asset="eza_${musl}.tar.gz"
      ;;
    aarch64)
      nvim_arch=arm64 fzf_arch=arm64 ff_arch=aarch64 jq_arch=arm64
      tldr_arch=aarch64 oc_arch=arm64
      lf_arch=arm64 ytdlp_asset=yt-dlp_linux_aarch64 lazygit_arch=arm64 gh_arch=arm64
      eza_asset="eza_aarch64-unknown-linux-gnu.tar.gz"
      ;;
    *)
      return 1
      ;;
  esac

  case $id in
    fd)
      printf '%s||tar|fd|fd\n' \
        "$GH/sharkdp/fd/releases/download/v10.5.2/fd-v10.5.2-${musl}.tar.gz"
      ;;
    rg)
      printf '%s|auto|tar|rg|rg\n' \
        "$GH/BurntSushi/ripgrep/releases/download/16.0.0/ripgrep-16.0.0-${musl}.tar.gz"
      ;;
    nvim)
      printf '%s||nvim|nvim|nvim\n' \
        "$GH/neovim/neovim/releases/download/v0.12.6/nvim-linux-${nvim_arch}.tar.gz"
      ;;
    fastfetch)
      printf '%s||tar|fastfetch|fastfetch\n' \
        "$GH/fastfetch-cli/fastfetch/releases/download/2.71.0/fastfetch-linux-${ff_arch}.tar.gz"
      ;;
    fzf)
      printf '%s||tar|fzf|fzf\n' \
        "$GH/junegunn/fzf/releases/download/v0.75.0/fzf-0.75.0-linux_${fzf_arch}.tar.gz"
      ;;
    bat)
      printf '%s||tar|bat|bat\n' \
        "$GH/sharkdp/bat/releases/download/v0.26.1/bat-v0.26.1-${musl}.tar.gz"
      ;;
    eza)
      printf '%s||tar|eza|eza\n' \
        "$GH/eza-community/eza/releases/download/v0.23.5/${eza_asset}"
      ;;
    zoxide)
      printf '%s||tar|zoxide|zoxide\n' \
        "$GH/ajeetdsouza/zoxide/releases/download/v0.10.0/zoxide-0.10.0-${musl}.tar.gz"
      ;;
    btop)
      printf '%s||tar|btop|btop\n' \
        "$GH/aristocratos/btop/releases/download/v1.4.8/btop-${musl}.tar.gz"
      ;;
    jq)
      printf '%s||raw|jq|jq\n' \
        "$GH/jqlang/jq/releases/download/jq-1.8.2/jq-linux-${jq_arch}"
      ;;
    tldr)
      printf '%s|auto|raw|tealdeer|tldr\n' \
        "$GH/tealdeer-rs/tealdeer/releases/download/v1.9.1/tealdeer-linux-${tldr_arch}-musl"
      ;;
    starship)
      printf '%s|auto|tar|starship|starship\n' \
        "$GH/starship/starship/releases/download/v1.27.0/starship-${musl}.tar.gz"
      ;;
    tetris)
      # Upstream publishes one x86-64 ELF and nothing else.
      if [[ $TRIPLE == x86_64 ]]; then
        printf '%s||raw|tetris-cli|tetris-cli\n' \
          "$GH/blueOkiris/tetris-cli/releases/download/v26.61.1/tetris-cli"
      fi
      ;;
    opencode)
      printf '%s||tar|opencode|opencode\n' \
        "$OPENCODE_BASE/opencode-linux-${oc_arch}.tar.gz"
      ;;
    lsd)
      printf '%s||tar|lsd|lsd\n' \
        "$GH/lsd-rs/lsd/releases/download/v1.2.0/lsd-v1.2.0-${musl}.tar.gz"
      ;;
    lf)
      printf '%s||tar|lf|lf\n' \
        "$GH/gokcehan/lf/releases/download/r42/lf-linux-${lf_arch}.tar.gz"
      ;;
    yt-dlp)
      printf '%s||raw|yt-dlp|yt-dlp\n' \
        "$GH/yt-dlp/yt-dlp/releases/download/2026.10.26/${ytdlp_asset}"
      ;;
    lazygit)
      printf '%s||tar|lazygit|lazygit\n' \
        "$GH/jesseduffield/lazygit/releases/download/v0.66.3/lazygit_0.66.3_linux_${lazygit_arch}.tar.gz"
      ;;
    gh)
      printf '%s||tar|gh|gh\n' \
        "$GH/cli/cli/releases/download/v2.105.0/gh_2.105.0_linux_${gh_arch}.tar.gz"
      ;;
    yazi)
      printf '%s||zip|yazi|yazi\n' \
        "$GH/sxyazi/yazi/releases/download/v26.9.1/yazi-${musl}.zip"
      ;;
    dysk)
      printf '%s||tar|dysk|dysk\n' \
        "$GH/Canop/dysk/releases/download/v3.8.2/dysk-v3.8.2-${musl}.tar.gz"
      ;;
    *)
      return 1
      ;;
  esac
}

install_nvim_tree() { # extracted-dir
  local root target="$OPT_DIR/nvim"
  if ! root=$(find_bin "$1" nvim); then
    warn "nvim binary not found in archive"
    return 1
  fi
  root=$(dirname "$(dirname "$root")")
  rm -rf "$target"
  mkdir -p "$OPT_DIR"
  mv "$root" "$target"
  ln -sfn "../opt/nvim/bin/nvim" "$BIN_DIR/nvim"
}

install_portable() { # id : 0 ok, 1 failed, 2 skipped
  local id=$1 rec url sha kind bin dest
  local work file found

  if ! rec=$(portable_record "$id"); then
    warn "no asset recipe for $id on $TRIPLE"
    return 1
  fi
  IFS='|' read -r url sha kind bin dest <<<"$rec"

  if [[ -z $url ]]; then
    note "$id: no prebuilt binary for $TRIPLE upstream; skipped"
    return 2
  fi

  ensure_workdir
  work=$(mktemp -d "$WORKDIR/item.XXXXXX")
  file="$work/download"

  printf '  fetching %s\n' "$url"
  if ! download "$url" "$file"; then
    warn "download failed: $url"
    return 1
  fi
  if [[ $sha == auto ]] && ! verify_sha256 "$file" "$url.sha256"; then
    return 1
  fi

  case $kind in
    raw)
      install -m 0755 "$file" "$BIN_DIR/$dest"
      ;;
    tar)
      if ! extract_tar "$file" "$work/tree"; then
        return 1
      fi
      if ! found=$(find_bin "$work/tree" "$bin"); then
        warn "binary '$bin' not found in archive for $id"
        return 1
      fi
      install -m 0755 "$found" "$BIN_DIR/$dest"
      ;;
    nvim)
      if ! extract_tar "$file" "$work/tree"; then
        return 1
      fi
      install_nvim_tree "$work/tree"
      ;;
    zip)
      if ! extract_zip "$file" "$work/tree"; then
        return 1
      fi
      if ! found=$(find_bin "$work/tree" "$bin"); then
        warn "binary '$bin' not found in archive for $id"
        return 1
      fi
      install -m 0755 "$found" "$BIN_DIR/$dest"
      # yazi ships a companion binary, ya, next to yazi. python3's zipfile
      # backend does not restore modes, so test for the file, not -x.
      if [[ -f "$(dirname "$found")/ya" ]]; then
        install -m 0755 "$(dirname "$found")/ya" "$BIN_DIR/ya"
      fi
      ;;
    *)
      warn "unknown archive kind '$kind' for $id"
      return 1
      ;;
  esac
}

# ------------------------------------------------------------ brew support

brew_env() {
  case ":$PATH:" in
    *":$BREW/bin:"*) ;;
    *) export PATH="$BREW/bin:$BREW/sbin:$PATH" ;;
  esac
  export HOMEBREW_NO_AUTO_UPDATE=1
  export HOMEBREW_NO_ANALYTICS=1
  export HOMEBREW_NO_ENV_HINTS=1
  export HOMEBREW_NO_INSTALL_CLEANUP=1
  export NONINTERACTIVE=1
  # Container runtimes often let brew's bwrap see a writable prefix, which
  # makes brew refuse to run. Only relax that inside a known container.
  if [[ -e /.dockerenv || -e /run/.containerenv ]]; then
    export HOMEBREW_NO_SANDBOX_LINUX=1
  fi
}

ensure_brew() {
  if [[ $BREW_FAILED == 1 ]]; then
    note "Homebrew bootstrap already failed; not retrying"
    return 1
  fi
  brew_env
  if [[ -x "$BREW/bin/brew" ]]; then
    return 0
  fi

  note "installing Homebrew into $BREW (rootless untar)"
  ensure_workdir
  local tarball="$WORKDIR/homebrew.tar.gz"
  # Homebrew dropped the master branch, so main is the supported tarball.
  # master stays as a fallback for older mirrors.
  if ! download "$GH/Homebrew/brew/tarball/main" "$tarball"; then
    if ! download "$GH/Homebrew/brew/tarball/master" "$tarball"; then
      warn "Homebrew download failed"
      BREW_FAILED=1
      return 1
    fi
  fi
  mkdir -p "$BREW"
  if ! tar xz --strip 1 -f "$tarball" -C "$BREW"; then
    warn "Homebrew extraction failed"
    BREW_FAILED=1
    return 1
  fi
  brew_env
  if ! "$BREW/bin/brew" --version >/dev/null; then
    warn "Homebrew does not run on this system"
    BREW_FAILED=1
    return 1
  fi
}

warn_missing_compiler() {
  if ! command -v cc >/dev/null 2>&1 && ! command -v gcc >/dev/null 2>&1; then
    warn "no C compiler (cc/gcc) found; bottles are preferred, but a formula with no usable bottle may still attempt a source build and fail"
  fi
}

install_brew() { # id : 0 ok, 1 failed, 2 skipped
  local id=$1 log
  if [[ $SKIP_BREW == 1 ]]; then
    note "$id: skipped (--skip-brew)"
    return 2
  fi
  if ! ensure_brew; then
    return 1
  fi
  brew_env
  ensure_workdir
  log="$WORKDIR/brew-$id.log"

  if "$BREW/bin/brew" install --formula --force-bottle "$id" >"$log" 2>&1; then
    return 0
  fi

  if grep -qF 'has no bottle' "$log"; then
    warn "no $id bottle exists for this system/platform; skipped instead of building from source"
    return 2
  fi

  warn "brew install $id failed; last log lines:"
  tail -n 5 "$log" >&2
  return 1
}

install_item() { # id : 0 ok, 1 failed, 2 skipped
  local id=$1
  case $(tool_method "$id") in
    brew) install_brew "$id" ;;
    portable) install_portable "$id" ;;
    *)
      warn "unknown install method for $id"
      return 1
      ;;
  esac
}

# ---------------------------------------------------------------- PATH block

# shellcheck disable=SC2016 # $HOME must stay literal in the generated block.
PATH_BLOCK='# >>> nithitsuki tools >>>
if [ -d "$HOME/.local/bin" ]; then
  case ":$PATH:" in
    *":$HOME/.local/bin:"*) ;;
    *) PATH="$HOME/.local/bin:$PATH" ;;
  esac
fi
if [ -d "$HOME/.linuxbrew/bin" ]; then
  case ":$PATH:" in
    *":$HOME/.linuxbrew/bin:"*) ;;
    *) PATH="$HOME/.linuxbrew/bin:$PATH" ;;
  esac
fi
export PATH
# <<< nithitsuki tools <<<'

ensure_path_block() { # file
  local file=$1 target
  # Never write through a symlink: ~/.zshrc is often a stow link into
  # ~/.dotfiles, and appending there would dirty the dotfiles repo.
  if [[ -L $file ]]; then
    target=$(readlink -f "$file" 2>/dev/null || readlink "$file")
    printf '  skipped PATH block for %s: it is a symlink to %s\n' "$file" "${target:-?}"
    return 0
  fi
  if [[ -e $file && ! -f $file ]]; then
    warn "$file is not a regular file; skipping the PATH block"
    return 0
  fi
  if [[ ! -e $file ]]; then
    if [[ $file != "$HOME/.profile" ]]; then
      return 0
    fi
    if ! : >"$file"; then
      warn "could not create $file; skipping the PATH block"
      return 0
    fi
  fi
  if grep -qF "$MARK_BEGIN" "$file"; then
    return 0
  fi
  if ! printf '\n%s\n' "$PATH_BLOCK" >>"$file" 2>/dev/null; then
    warn "could not write the PATH block to $file"
    return 0
  fi
  printf '  added PATH block to %s\n' "$file"
}

setup_environment() {
  mkdir -p "$BIN_DIR" "$OPT_DIR"
  export PATH="$BIN_DIR:$PATH"

  ensure_path_block "$HOME/.profile"
  ensure_path_block "$HOME/.bashrc"
  ensure_path_block "$HOME/.zshrc"

  if [[ -d "$BREW/bin" && ":$PATH:" != *":$BREW/bin:"* ]]; then
    export PATH="$BREW/bin:$PATH"
  fi
}

# --------------------------------------------------------------------- menu

print_menu() {
  local i id mark status
  printf '\n'
  for i in "${!TOOL_IDS[@]}"; do
    id=${TOOL_IDS[$i]}
    if [[ ${SELECTED[$id]:-0} == 1 ]]; then
      mark='x'
    else
      mark=' '
    fi
    if tool_present "$id"; then
      status='installed'
    else
      status=''
    fi
    printf ' %2d) [%s] %-9s %-9s %s\n' \
      "$((i + 1))" "$mark" "$id" "$(tool_method "$id")" "$status"
  done
}

# ------------------------------------------------------------- TUI picker

# Restores cursor and attributes. Safe to call at any time; only prints while
# the TUI is active.
tui_restore() {
  if [[ $TUI_ACTIVE == 1 ]]; then
    printf '\033[0m\033[?25h'
    # read -n can leave echo/icanon off if a signal kills it mid-read.
    if [[ -n $TUI_TTY_STATE ]] && command -v stty >/dev/null 2>&1; then
      stty "$TUI_TTY_STATE" <&"$TTY_FD" 2>/dev/null || true
    fi
    TUI_TTY_STATE=""
    TUI_ACTIVE=0
  fi
}

tui_save_tty() {
  TUI_TTY_STATE=""
  if command -v stty >/dev/null 2>&1; then
    TUI_TTY_STATE=$(stty -g <&"$TTY_FD" 2>/dev/null || true)
  fi
}

tui_size() {
  local size="" rows=0 cols=0
  TUI_ROWS=24
  TUI_COLS=80
  if command -v stty >/dev/null 2>&1; then
    size=$(stty size <&"$TTY_FD" 2>/dev/null || true)
  fi
  size=${size//$'\r'/}
  if [[ $size =~ ^([0-9]+)[[:space:]]+([0-9]+)$ ]]; then
    rows=${BASH_REMATCH[1]}
    cols=${BASH_REMATCH[2]}
  fi
  # A PTY can report 0x0 before anyone sets a size; that is unknown, not tiny.
  if ((rows == 0 || cols == 0)) && command -v tput >/dev/null 2>&1; then
    rows=$(tput lines 2>/dev/null || printf 0)
    cols=$(tput cols 2>/dev/null || printf 0)
    rows=${rows//$'\r'/}
    cols=${cols//$'\r'/}
    [[ $rows =~ ^[0-9]+$ ]] || rows=0
    [[ $cols =~ ^[0-9]+$ ]] || cols=0
  fi
  if ((rows > 0 && cols > 0)); then
    TUI_ROWS=$rows
    TUI_COLS=$cols
  fi
  if ((TUI_ROWS < 10)); then
    TUI_ROWS=10
  fi
  if ((TUI_COLS < 40)); then
    TUI_COLS=40
  fi
}

# Flatten groups and items into one display list; group rows are not selectable.
tui_build() {
  local group id
  TUI_KIND=()
  TUI_ID=()
  for group in "${TOOL_GROUPS[@]}"; do
    TUI_KIND+=("group")
    TUI_ID+=("$group")
    for id in "${TOOL_IDS[@]}"; do
      [[ $(tool_group "$id") == "$group" ]] || continue
      TUI_KIND+=("item")
      TUI_ID+=("$id")
    done
  done
  TUI_CUR=1
  TUI_TOP=0
}

tui_move() { # delta
  local delta=$1 i=$TUI_CUR last=$((${#TUI_KIND[@]} - 1))
  while :; do
    i=$((i + delta))
    if ((i < 0)); then
      i=0
    fi
    if ((i > last)); then
      i=$last
    fi
    if [[ ${TUI_KIND[$i]} == item ]]; then
      break
    fi
    if ((i == 0 || i == last)); then
      break
    fi
  done
  if [[ ${TUI_KIND[$i]} == item ]]; then
    TUI_CUR=$i
  fi
}

tui_home() {
  local i=0 last=$((${#TUI_KIND[@]} - 1))
  while ((i <= last)) && [[ ${TUI_KIND[$i]} != item ]]; do
    i=$((i + 1))
  done
  if ((i <= last)); then
    TUI_CUR=$i
  fi
  TUI_TOP=0
}

tui_end() {
  local i=$((${#TUI_KIND[@]} - 1))
  while ((i > 0)) && [[ ${TUI_KIND[$i]} != item ]]; do
    i=$((i - 1))
  done
  TUI_CUR=$i
}

tui_toggle() {
  local id=${TUI_ID[$TUI_CUR]}
  if [[ ${SELECTED[$id]:-0} == 1 ]]; then
    SELECTED[$id]=0
  else
    SELECTED[$id]=1
  fi
}

tui_pad() { # text -> TUI_TEXT, padded/truncated to one screen line
  local text=$1 max=$((TUI_COLS - 1))
  printf -v TUI_TEXT '%-*s' "$max" "$text"
  TUI_TEXT=${TUI_TEXT:0:$max}
}

tui_draw() {
  local capacity=$((TUI_ROWS - 5))
  if ((capacity < 5)); then
    capacity=5
  fi
  local id kind marker count=0 i end last cur_id cur_desc cur_method
  last=$((${#TUI_KIND[@]} - 1))

  for id in "${TOOL_IDS[@]}"; do
    if [[ ${SELECTED[$id]:-0} == 1 ]]; then
      count=$((count + 1))
    fi
  done

  # Keep the cursor inside the scrolling viewport.
  if ((TUI_CUR < TUI_TOP)); then
    TUI_TOP=$TUI_CUR
  fi
  if ((TUI_CUR >= TUI_TOP + capacity)); then
    TUI_TOP=$((TUI_CUR - capacity + 1))
  fi
  if ((TUI_TOP > last - capacity + 1)); then
    TUI_TOP=$((last - capacity + 1))
  fi
  if ((TUI_TOP < 0)); then
    TUI_TOP=0
  fi

  TUI_BUF=$'\033[H'
  tui_pad ' Select terminal tools'
  TUI_BUF+=$'\033[1m'"$TUI_TEXT"$'\033[0m\033[K\r\n'
  TUI_BUF+=$'\033[K\r\n'

  end=$((TUI_TOP + capacity))
  for ((i = TUI_TOP; i < end; i++)); do
    if ((i > last)); then
      TUI_BUF+=$'\033[K\r\n'
      continue
    fi
    kind=${TUI_KIND[$i]}
    id=${TUI_ID[$i]}
    if [[ $kind == group ]]; then
      tui_pad "  $id"
      TUI_BUF+=$'\033[1m'"$TUI_TEXT"$'\033[0m\033[K\r\n'
      continue
    fi
    if [[ ${SELECTED[$id]:-0} == 1 ]]; then
      marker='[x]'
    else
      marker='[ ]'
    fi
    tui_pad "  $marker $id"
    if ((i == TUI_CUR)); then
      TUI_BUF+=$'\033[7m'"$TUI_TEXT"$'\033[0m\033[K\r\n'
    else
      TUI_BUF+="$TUI_TEXT"$'\033[K\r\n'
    fi
  done

  TUI_BUF+=$'\033[K\r\n'
  cur_id=${TUI_ID[$TUI_CUR]}
  cur_desc=$(tool_desc "$cur_id")
  cur_method=$(tool_method "$cur_id")
  local suffix="  [$cur_method]" ellipsis ell_len
  case ${LC_ALL:-${LC_CTYPE:-${LANG:-}}} in
    '' | C | POSIX) ellipsis='...' ;;
    *) ellipsis=$(printf '\u2026') ;;
  esac
  ell_len=${#ellipsis}
  local desc_room line_max line_text
  line_max=$((TUI_COLS - 1))
  desc_room=$((line_max - 2 - ${#suffix}))
  line_text="  $cur_desc$suffix"
  if ((desc_room > ell_len)); then
    if ((${#cur_desc} + ell_len > desc_room)); then
      cur_desc="${cur_desc:0:$((desc_room - ell_len))}$ellipsis"
      line_text="  $cur_desc$suffix"
    fi
  else
    line_text=${line_text:0:$line_max}
  fi
  tui_pad "$line_text"
  TUI_BUF+="$TUI_TEXT"$'\033[K\r\n'
  local footer
  if ((TUI_COLS >= 100)); then
    footer="  Up/Down or j/k move  space toggle  a all  n none  d defaults  enter install  q quit  ${count} selected"
  else
    footer="  j/k move  space toggle  a/n/d  enter install  q quit  ${count} selected"
  fi
  # Very narrow terminals cannot show even the compact hints; shorten again
  # rather than cut the selected count off the end.
  if ((${#footer} > line_max)); then
    footer="  j/k space a/n/d enter q  ${count} selected"
  fi
  tui_pad "$footer"
  # No trailing newline: writing one more line than the screen has would
  # scroll the title off the top.
  TUI_BUF+=$'\033[2m'"$TUI_TEXT"$'\033[0m\033[K'
  printf '%s' "$TUI_BUF"
}

# Sets TUI_KEY and returns 0, or returns 1 on EOF. Runs in the main shell so
# signals (INT/TERM/WINCH) are handled while the read is blocked.
tui_read_key() {
  local key rest="" status=0
  TUI_KEY="none"
  IFS= read -rsn1 -d '' -u "$TTY_FD" key || status=$?
  if ((status > 128)); then
    # Interrupted by a trapped signal such as SIGWINCH; redraw next round.
    return 0
  fi
  if ((status != 0)); then
    return 1
  fi
  case $key in
    '' | $'\r' | $'\n') TUI_KEY=enter ;;
    ' ') TUI_KEY=space ;;
    $'\x1b')
      rest=""
      if ! IFS= read -rsn1 -d '' -t 0.05 -u "$TTY_FD" rest; then
        TUI_KEY=esc
        return 0
      fi
      if [[ $rest == '[' ]]; then
        rest=""
        IFS= read -rsn1 -d '' -t 0.05 -u "$TTY_FD" rest || true
        case $rest in
          A) TUI_KEY=up ;;
          B) TUI_KEY=down ;;
          H) TUI_KEY=home ;;
          F) TUI_KEY=end ;;
          *) TUI_KEY=none ;;
        esac
      elif [[ $rest == 'O' ]]; then
        rest=""
        IFS= read -rsn1 -d '' -t 0.05 -u "$TTY_FD" rest || true
        case $rest in
          A) TUI_KEY=up ;;
          B) TUI_KEY=down ;;
          H) TUI_KEY=home ;;
          F) TUI_KEY=end ;;
          *) TUI_KEY=none ;;
        esac
      else
        # Alt+letter and other ESC-prefixed input is not a command.
        TUI_KEY=none
      fi
      ;;
    *) TUI_KEY=$key ;;
  esac
  return 0
}

menu_tui() {
  local rc=0
  tui_size
  tui_build
  tui_save_tty
  TUI_ACTIVE=1
  trap 'tui_restore; exit 130' INT
  trap 'tui_restore; exit 143' TERM
  trap 'TUI_RESIZED=1' WINCH
  printf '\033[?25l\033[2J'
  while :; do
    if [[ $TUI_RESIZED == 1 ]]; then
      TUI_RESIZED=0
      tui_size
    fi
    tui_draw
    if ! tui_read_key; then
      rc=1
      break
    fi
    case $TUI_KEY in
      up | k) tui_move -1 ;;
      down | j) tui_move 1 ;;
      space) tui_toggle ;;
      a) select_all ;;
      n) select_none ;;
      d) select_defaults ;;
      home) tui_home ;;
      end) tui_end ;;
      none) ;;
      enter)
        rc=0
        break
        ;;
      q | esc)
        rc=1
        break
        ;;
    esac
  done
  tui_restore
  trap - INT TERM WINCH
  printf '\033[2J\033[H'
  return "$rc"
}

menu_text() {
  local reply n i id
  local -a answers
  while :; do
    print_menu
    printf '\nEnter=install  a=all  n=none  d=defaults  numbers toggle (e.g. 1 3 4)\n'
    if ! ask '> '; then
      printf '\n'
      return 1
    fi
    reply=${ASK_REPLY//,/ }
    case $reply in
      '')
        printf '\n'
        return 0
        ;;
      a | A) select_all ;;
      n | N) select_none ;;
      d | D) select_defaults ;;
      *)
        read -r -a answers <<<"$reply"
        for n in "${answers[@]}"; do
          if [[ $n =~ ^[0-9]+$ ]]; then
            i=$((n - 1))
            if ((i >= 0 && i < ${#TOOL_IDS[@]})); then
              id=${TOOL_IDS[$i]}
              if [[ ${SELECTED[$id]:-0} == 1 ]]; then
                SELECTED[$id]=0
              else
                SELECTED[$id]=1
              fi
            else
              printf 'no item %s\n' "$n"
            fi
          else
            printf 'unknown command: %s\n' "$n"
          fi
        done
        ;;
    esac
  done
}

# ------------------------------------------------------------------ reports

print_catalogue() {
  local group id bin method status mark total=0
  for group in "${TOOL_GROUPS[@]}"; do
    printf '\n%s\n' "$group"
    for id in "${TOOL_IDS[@]}"; do
      [[ $(tool_group "$id") == "$group" ]] || continue
      bin=$(tool_bin "$id")
      [[ -z $bin ]] && bin='-'
      method=$(tool_method "$id")
      if tool_present "$id"; then
        status=installed
      else
        status=missing
      fi
      if [[ $(tool_default "$id") == 1 ]]; then
        mark='*'
      else
        mark=' '
      fi
      printf '  %-23s %s %-12s %-9s %-9s %s\n' \
        "$id" "$mark" "$bin" "$method" "$status" "$(tool_desc "$id")"
      total=$((total + 1))
    done
  done
  printf '\n%d tools in %d groups\n' "$total" "${#TOOL_GROUPS[@]}"
  printf '* = default\n'
}

print_plan() {
  local id
  local -a would=() have=() skipped=()
  for id in "${TOOL_IDS[@]}"; do
    [[ ${SELECTED[$id]:-0} == 1 ]] || continue
    if [[ $(tool_method "$id") == brew && $SKIP_BREW == 1 ]]; then
      skipped+=("$id")
    elif [[ $FORCE == 0 ]] && tool_present "$id"; then
      have+=("$id")
    else
      would+=("$id")
    fi
  done

  printf 'Dry run: no downloads, directories or shell files are touched.\n'
  printf '  would install (%d): %s\n' "${#would[@]}" "$(join_list "${would[@]}")"
  printf '  already present (%d): %s\n' "${#have[@]}" "$(join_list "${have[@]}")"
  printf '  would skip (%d): %s\n' "${#skipped[@]}" "$(join_list "${skipped[@]}")"
  printf '  install root: %s\n' "$BIN_DIR"
  if [[ $NO_DOTFILES == 0 ]]; then
    printf '  the dotfiles step would be offered at the end (pass --no-dotfiles to skip)\n'
  fi
}

print_summary() {
  printf '\nSummary\n'
  printf '  installed (%d): %s\n' "${#INSTALLED[@]}" "$(join_list "${INSTALLED[@]}")"
  printf '  already present (%d): %s\n' "${#PRESENT[@]}" "$(join_list "${PRESENT[@]}")"
  printf '  skipped (%d): %s\n' "${#SKIPPED[@]}" "$(join_list "${SKIPPED[@]}")"
  printf '  failed (%d): %s\n' "${#FAILED[@]}" "$(join_list "${FAILED[@]}")"

  printf '\nManual notes:\n'
  # shellcheck disable=SC2016 # $PATH must stay literal for the user's shell
  printf '  - Open a new shell (or run: export PATH="%s:$PATH") to use new tools.\n' "$BIN_DIR"
  local note_line
  for note_line in "${NOTES[@]}"; do
    printf '  - %s\n' "$note_line"
  done
  if [[ ${#FAILED[@]} -eq 0 ]]; then
    printf '  - Nothing failed.\n'
  fi
}

# ------------------------------------------------------------------ dotfiles

ensure_git() {
  command -v git >/dev/null 2>&1 && return 0
  [[ -x "$BREW/bin/git" ]] && return 0
  return 1
}

ensure_stow() {
  command -v stow >/dev/null 2>&1 && return 0
  [[ -x "$BREW/bin/stow" ]] && return 0
  if ! [[ -x "$BREW/bin/brew" ]]; then
    return 1
  fi
  if ! ask 'stow is missing; install it with Homebrew? [y/N] '; then
    return 1
  fi
  case ${ASK_REPLY:-} in
    y | Y | yes | YES) brew_env && "$BREW/bin/brew" install --formula stow ;;
    *) return 1 ;;
  esac
}

dotfiles_step() {
  if [[ $NO_DOTFILES == 1 || $INTERACTIVE == 0 ]]; then
    printf '\ndotfiles: skipped (non-interactive or --no-dotfiles)\n'
    return 0
  fi

  printf '\n'
  if ! ask 'Install dotfiles from github.com/nithitsuki/dotfiles? [y/N] '; then
    printf '\ndotfiles: skipped\n'
    return 0
  fi
  case ${ASK_REPLY:-} in
    y | Y | yes | YES) ;;
    *)
      printf 'dotfiles: skipped\n'
      return 0
      ;;
  esac

  if ! ensure_git; then
    printf 'dotfiles: skipped, git is not available\n'
    return 0
  fi

  # Check stow before cloning, so a missing stow cannot leave an unused checkout.
  if ! ensure_stow; then
    printf 'dotfiles: skipped, stow is not available\n'
    return 0
  fi

  if [[ ! -d "$HOME/.dotfiles" ]]; then
    if ! git clone https://github.com/nithitsuki/dotfiles.git "$HOME/.dotfiles"; then
      warn "dotfiles clone failed"
      return 0
    fi
  else
    if ! git -C "$HOME/.dotfiles" pull --ff-only; then
      warn "dotfiles update failed, keeping the existing checkout"
      return 0
    fi
  fi

  if [[ -d "$BREW/bin" && ":$PATH:" != *":$BREW/bin:"* ]]; then
    export PATH="$BREW/bin:$PATH"
  fi

  if [[ -f "$HOME/.dotfiles/run.sh" ]]; then
    if ! bash "$HOME/.dotfiles/run.sh"; then
      warn "dotfiles run.sh failed; continuing with the summary"
    fi
  else
    warn "no run.sh in $HOME/.dotfiles"
  fi
}

# --------------------------------------------------------------------- main

usage() {
  cat <<'EOF'
setup-user-tools.sh - rootless installer for terminal tools.

Usage:
  setup-user-tools.sh [--all] [--only LIST] [--skip-brew] [--no-dotfiles]
                      [--dry-run] [--list] [--force] [--text-menu] [-h|--help]

  --all              install everything, no menu
  --only fd,rg,nvim  install just these ids (see --list)
  --skip-brew        never install Homebrew; skip brew-only items
  --no-dotfiles      do not offer the dotfiles step
  --dry-run          print the plan and change nothing
  --list             print the catalogue and stop
  --force            reinstall items that look present
  --text-menu        use the plain line menu instead of the full-screen picker

Binaries go to ~/.local/bin, trees to ~/.local/opt, Homebrew to ~/.linuxbrew.
It never uses sudo or a system package manager.
EOF
}

parse_args() {
  while (($# > 0)); do
    case $1 in
      --all) ALL=1 ;;
      --only)
        shift
        ONLY=${1:-}
        [[ -z $ONLY ]] && die "--only needs a comma list, e.g. --only fd,rg"
        ;;
      --only=*)
        ONLY=${1#*=}
        if [[ -z $ONLY ]]; then
          die "--only needs a comma list, e.g. --only fd,rg"
        fi
        ;;
      --skip-brew) SKIP_BREW=1 ;;
      --no-dotfiles) NO_DOTFILES=1 ;;
      --dry-run) DRY_RUN=1 ;;
      --list) LIST=1 ;;
      --force) FORCE=1 ;;
      --text-menu) TEXT_MENU=1 ;;
      -h | --help)
        usage
        exit 0
        ;;
      *) die "unknown option: $1 (try --help)" ;;
    esac
    shift
  done

  if [[ -n $ONLY && $ALL == 1 ]]; then
    die "--all and --only are mutually exclusive"
  fi
}

run_installs() {
  local id status
  for id in "${TOOL_IDS[@]}"; do
    [[ ${SELECTED[$id]:-0} == 1 ]] || continue

    if [[ $FORCE == 0 ]] && tool_present "$id"; then
      printf '[present] %s\n' "$id"
      PRESENT+=("$id")
      continue
    fi

    printf '[install] %s (%s)\n' "$id" "$(tool_method "$id")"
    status=0
    # No subshell: WORKDIR and the EXIT trap must stay in this shell so the
    # temp dir is cleaned up. The if-context already disables set -e.
    if install_item "$id"; then
      status=0
    else
      status=$?
    fi

    case $status in
      0)
        printf '[ok]      %s\n' "$id"
        INSTALLED+=("$id")
        ;;
      2)
        printf '[skip]    %s\n' "$id"
        SKIPPED+=("$id")
        ;;
      *)
        printf '[fail]    %s\n' "$id"
        FAILED+=("$id")
        ;;
    esac
  done
}

add_manual_notes() {
  if [[ ${SELECTED[zsh]:-0} == 1 && -x "$BREW/bin/zsh" ]]; then
    NOTES+=("zsh is installed at $BREW/bin/zsh but cannot become your login shell without root approval; try it now with: $BREW/bin/zsh")
    NOTES+=("after making it a login shell: chsh -s $BREW/bin/zsh (the shell must be listed in /etc/shells)")
  fi

  if [[ ${SELECTED[yt-dlp]:-0} == 1 ]]; then
    if [[ ${SELECTED[ffmpeg]:-0} != 1 ]] && ! command -v ffmpeg >/dev/null 2>&1; then
      NOTES+=("yt-dlp: audio extraction needs ffmpeg, which is not selected or on PATH; install it with --only ffmpeg")
    fi
  fi

  if [[ ${SELECTED[zsh-autosuggestions]:-0} == 1 ]] && tool_present zsh-autosuggestions; then
    # shellcheck disable=SC2016 # $HOME must stay literal for the user's shell
    NOTES+=('zsh-autosuggestions: add to ~/.zshrc: source "$HOME/.linuxbrew/share/zsh-autosuggestions/zsh-autosuggestions.zsh"')
  fi
  if [[ ${SELECTED[zsh-syntax-highlighting]:-0} == 1 ]] && tool_present zsh-syntax-highlighting; then
    # shellcheck disable=SC2016 # $HOME must stay literal for the user's shell
    NOTES+=('zsh-syntax-highlighting: add to ~/.zshrc: source "$HOME/.linuxbrew/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh"')
  fi
  if [[ ${SELECTED[zsh-completions]:-0} == 1 ]] && tool_present zsh-completions; then
    # shellcheck disable=SC2016 # $HOME must stay literal for the user's shell
    NOTES+=('zsh-completions: add to ~/.zshrc: fpath+=("$HOME/.linuxbrew/share/zsh-completions") then: autoload -Uz compinit && compinit')
  fi
  if [[ ${SELECTED[zsh-autocomplete]:-0} == 1 ]] && tool_present zsh-autocomplete; then
    # shellcheck disable=SC2016 # $HOME must stay literal for the user's shell
    NOTES+=('zsh-autocomplete: add to ~/.zshrc: source "$HOME/.linuxbrew/share/zsh-autocomplete/zsh-autocomplete.plugin.zsh"')
  fi

  if [[ ${SELECTED[tetris]:-0} == 1 && $TRIPLE != x86_64 ]]; then
    NOTES+=("tetris-cli has no $TRIPLE build upstream; it was skipped on this machine")
  fi
}

main() {
  if [[ $EUID -eq 0 ]]; then
    die "do not run this as root; it installs into your home directory"
  fi

  parse_args "$@"

  TRIPLE=$(uname -m)
  case $TRIPLE in
    x86_64 | aarch64) ;;
    *) die "unsupported architecture: $TRIPLE (this script supports x86_64 and aarch64)" ;;
  esac

  setup_tty

  select_defaults

  if [[ $LIST == 1 ]]; then
    print_catalogue
    exit 0
  fi

  if [[ $ALL == 1 ]]; then
    select_all
  elif [[ -n $ONLY ]]; then
    select_only "$ONLY"
  elif [[ $INTERACTIVE == 1 ]]; then
    if [[ $TEXT_MENU == 1 || -z ${TERM:-} || ${TERM:-} == dumb ]]; then
      if ! menu_text; then
        printf 'cancelled\n'
        exit 1
      fi
    else
      if ! menu_tui; then
        printf 'cancelled\n'
        exit 1
      fi
    fi
  else
    print_catalogue
    printf '\nerror: no terminal available (stdin is not a tty and /dev/tty cannot be opened).\n' >&2
    printf '       Pass --all to install everything, or --only fd,rg,nvim to choose.\n' >&2
    exit 1
  fi

  if ! any_selected; then
    printf 'nothing selected, nothing to do\n'
    exit 0
  fi

  if [[ $DRY_RUN == 1 ]]; then
    print_plan
    exit 0
  fi

  setup_environment

  if has_brew_selection && [[ $SKIP_BREW == 0 ]]; then
    warn_missing_compiler
  fi

  run_installs
  add_manual_notes
  dotfiles_step
  print_summary

  if [[ ${#FAILED[@]} -gt 0 ]]; then
    exit 1
  fi
  exit 0
}

main "$@"
