#!/usr/bin/env bash
# dot — manage this dev environment.  Run `dot help`.
export USER=${USER:-$(id -un)}
set -euo pipefail

DOTFILES_DIR="${DOTFILES_DIR:-$HOME/.dotfiles}"
STATE_DIR="$HOME/.config/dotfiles"
SECRETS_ENV="$STATE_DIR/secrets.env"
GITEA_URL="https://gitea.godemperordoge.org"
WALLPAPER_REPO="$GITEA_URL/ziadarafat/wallpapers.git"
WALLPAPER_DIR="$HOME/Pictures/Wallpapers"
# Where wallpapers originally live on the Deck's external drive.
WALLPAPER_SRC_WORK="${WALLPAPER_SRC_WORK:-/run/media/deck/41e37da2-f67a-4c8c-96e8-78b21eab5bf6/backup/Pictures/ac_walls}"
WALLPAPER_SRC_PERSONAL="${WALLPAPER_SRC_PERSONAL:-/run/media/deck/41e37da2-f67a-4c8c-96e8-78b21eab5bf6/backup/Pictures/pokewalls/unprocessed}"

mkdir -p "$STATE_DIR"

c_blue=$'\e[34m'; c_yel=$'\e[33m'; c_red=$'\e[31m'; c_grn=$'\e[32m'; c_off=$'\e[0m'
step() { printf '%s==>%s %s\n' "$c_blue" "$c_off" "$*"; }
warn() { printf '%s!!%s  %s\n' "$c_yel" "$c_off" "$*" >&2; }
die()  { printf '%sxx%s  %s\n' "$c_red" "$c_off" "$*" >&2; exit 1; }
ok()   { printf '%sok%s  %s\n' "$c_grn" "$c_off" "$*"; }
have() { command -v "$1" >/dev/null 2>&1; }

os_id() { (. /etc/os-release 2>/dev/null && echo "${ID:-unknown}") || echo unknown; }
has_systemd() { [ -d /run/systemd/system ]; }
in_container() { [ -f /run/.containerenv ] || [ -f /.dockerenv ] || [ -n "${container:-}" ]; }

nix_ca_candidates() {
  printf '%s\n' "${SSL_CERT_FILE:-}" /etc/ssl/certs/ca-certificates.crt \
    /etc/pki/tls/certs/ca-bundle.crt /etc/ssl/cert.pem \
    "$HOME/.nix-profile/etc/ssl/certs/ca-bundle.crt"
}
configure_nix_tls() {
  # A shared home/session may carry the host's Debian CA path into Fedora/Alma.
  # Keep valid custom trust bundles; select a local bundle only when needed.
  [ -n "${NIX_SSL_CERT_FILE:-}" ] && [ -f "$NIX_SSL_CERT_FILE" ] && [ -r "$NIX_SSL_CERT_FILE" ] && return 0
  local cert
  while IFS= read -r cert; do
    if [ -f "$cert" ] && [ -r "$cert" ]; then
      export NIX_SSL_CERT_FILE="$cert"
      return 0
    fi
  done < <(nix_ca_candidates)
  return 0
}
source_nix() {
  if have nix; then configure_nix_tls; return 0; fi
  for f in "$HOME/.nix-profile/etc/profile.d/nix.sh" /nix/var/nix/profiles/default/etc/profile.d/nix-daemon.sh; do
    # shellcheck disable=SC1090
    [ -e "$f" ] && . "$f" && break
  done
  have nix || return 1
  configure_nix_tls
}

# sudo that works as root, with a TTY, or not at all.
SUDO() {
  if [ "$(id -u)" = 0 ]; then "$@"; elif have sudo; then sudo "$@"; else die "need root for: $*"; fi
}

# ---------------------------------------------------------------- profile
detect_profile() {
  if [ "${XDG_CURRENT_DESKTOP:-}" = KDE ] || pgrep -x plasmashell >/dev/null 2>&1 || have plasmashell; then
    echo full
  else
    echo headless
  fi
}

profile() {
  if [ -s "$STATE_DIR/profile" ]; then cat "$STATE_DIR/profile"; else detect_profile; fi
}

flake_attr() {
  local p; p="$(profile)"
  if [ "$p" = headless ] && [ "$(uname -m)" = aarch64 ]; then echo headless-aarch64; else echo "$p"; fi
}

is_desktop() { case "$(profile)" in full|full-work) return 0;; *) return 1;; esac; }

flatpak_apps() {
  local app
  while read -r app; do
    [[ -z "$app" || "$app" == \#* ]] && continue
    if [ "$(profile)" = full-work ]; then
      case "$app" in com.google.Chrome|org.telegram.desktop|dev.vencord.Vesktop|org.kde.krita) continue;; esac
    fi
    printf '%s\n' "$app"
  done <"$DOTFILES_DIR/config/flatpaks.txt"
}

cmd_profile() {
  case "${1:-}" in
    full|full-work|headless) echo "$1" >"$STATE_DIR/profile"; ok "profile set to $1 (run: dot switch)";;
    auto) rm -f "$STATE_DIR/profile"; ok "profile follows auto-detection ($(detect_profile))";;
    "") echo "$(profile)$( [ -s "$STATE_DIR/profile" ] || echo ' (auto)')";;
    *) die "usage: dot profile [full|full-work|headless|auto]";;
  esac
}

# ---------------------------------------------------------------- nix
nix_user_config() { printf '%s/nix/nix.conf\n' "${XDG_CONFIG_HOME:-$HOME/.config}"; }

ensure_nix_features() {
  local file dir tmp backup
  file="$(nix_user_config)"; dir="$(dirname "$file")"
  mkdir -p "$dir"
  # Home Manager links this file into /nix/store. Shared distrobox homes may
  # see the link but not its target; never append through a managed store link.
  if [ -L "$file" ] && [ ! -e "$file" ]; then
    backup="$(mktemp "$dir/nix.conf.broken-link.XXXXXX")"
    cp -P -- "$file" "$backup"
    warn "Nix config link is broken (shared container store?) — preserving it at $backup and creating a local bootstrap config"
  elif [ -e "$file" ] && [ ! -f "$file" ]; then
    die "Nix config is not a regular file: $file"
  fi
  # Append an additive setting, preserving unrelated settings and comments.
  if [ -f "$file" ] && grep -Eq '^[[:space:]]*(extra-)?experimental-features[[:space:]]*=[[:space:]]*nix-command[[:space:]]+flakes[[:space:]]*(#.*)?$' "$file"; then
    return 0
  fi
  tmp="$(mktemp "$dir/.nix.conf.dot.XXXXXX")"
  if [ -f "$file" ]; then
    if ! cat -- "$file" >"$tmp"; then rm -f "$tmp"; die "Cannot read existing Nix config: $file"; fi
  fi
  printf '\nextra-experimental-features = nix-command flakes\n' >>"$tmp"
  mv -f -- "$tmp" "$file"
}

cmd_nix() {
  ensure_nix_features
  if source_nix; then ok "nix $(nix --version | awk '{print $NF}') present"; return; fi
  local os; os="$(os_id)"
  if [ "$os" = steamos ] || ! has_systemd || in_container; then
    # Single-user: no daemon, nothing in /etc, so SteamOS updates can't break it.
    # SteamOS bind-mounts /nix from /home/.steamos/offload/nix, so it persists.
    step "installing Nix (single-user) into /nix"
    if [ ! -w /nix ] 2>/dev/null; then
      step "making /nix owned by $USER (one-time sudo)"
      SUDO install -d -m 0755 -o "$(id -u)" -g "$(id -g)" /nix
      SUDO chown "$(id -u):$(id -g)" /nix
    fi
    curl -fsSL https://nixos.org/nix/install | sh -s -- --no-daemon --no-modify-profile
  else
    step "installing Nix (multi-user, Determinate installer)"
    curl -fsSL https://install.determinate.systems/nix | sh -s -- install --no-confirm
  fi
  source_nix || die "nix installed but not on PATH; open a new shell and re-run"
}

# ---------------------------------------------------------------- home-manager
# Two home-manager runs in one home fight over the Nix store (git-minimal lock)
# and over ~/.local/state/nix/profiles. Serialise them instead of racing.
switch_lock() {
  local lock="$STATE_DIR/switch.lock"
  have flock || return 0
  exec 9>>"$lock" || return 0
  if ! flock -n 9; then
    warn "another dot switch/update is running (pid $(cat "$lock" 2>/dev/null || echo '?')); waiting for it to finish"
    flock 9 || die "cannot lock $lock"
  fi
  printf '%s\n' "$$" >"$lock"
}

cmd_switch() {
  [ -n "${1:-}" ] && cmd_profile "$1"
  switch_lock
  source_nix || die "nix missing: run dot nix"
  ensure_nix_features
  local attr backup_ext; attr="$(flake_attr)"
  # Shared homes can already have an hm-bak from a previous host/container.
  # Preserve old backups instead of making the recovery switch clobber one.
  backup_ext="hm-bak.$(date -u +%Y%m%dT%H%M%SZ).$$"
  step "home-manager switch → $attr"
  export DOTFILES_DIR
  if have home-manager; then
    home-manager switch --flake "$DOTFILES_DIR#$attr" --impure -b "$backup_ext"
  else
    nix run --inputs-from "$DOTFILES_DIR" home-manager -- switch --flake "$DOTFILES_DIR#$attr" --impure -b "$backup_ext"
  fi
}

# ---------------------------------------------------------------- distro layer (sudo)
install_pkgs() {
  local os; os="$(os_id)"
  if in_container; then
    case "$os" in
      fedora|almalinux|rhel|rocky) SUDO dnf install -y zsh git curl xz ;;
      arch|cachyos|endeavouros|manjaro) SUDO pacman -Sy --needed --noconfirm zsh git curl xz ;;
      debian|ubuntu) SUDO apt-get update && SUDO apt-get install -y zsh git curl xz-utils ;;
      *) warn "install zsh, git, curl and xz in this container" ;;
    esac
    return
  fi
  case "$os" in
    steamos) return 0 ;; # read-only /usr; SteamOS already ships zsh, podman, distrobox, flatpak, Konsole
    fedora)
      local p=(zsh git curl podman distrobox flatpak)
      is_desktop && p+=(konsole spectacle)
      SUDO dnf install -y "${p[@]}" ;;
    arch|cachyos|endeavouros|manjaro)
      local p=(zsh git curl podman distrobox flatpak xz)
      is_desktop && p+=(konsole spectacle kate)
      SUDO pacman -Sy --needed --noconfirm "${p[@]}" ;;
    almalinux|rhel|rocky)
      SUDO dnf install -y zsh git curl podman flatpak ;;
    debian|ubuntu)
      SUDO apt-get update && SUDO apt-get install -y zsh git curl podman distrobox flatpak xz-utils ;;
    *) warn "unknown distro '$os': install zsh, git, curl, podman, distrobox, flatpak yourself" ;;
  esac
}

browser_policies() {
  # Flathub Chrome/Edge merge host policies from /run/host/etc/opt/<browser>/policies.
  for b in chrome edge; do
    if [ "$b" = chrome ] && [ "$(profile)" = full-work ]; then
      SUDO rm -f /etc/opt/chrome/policies/managed/dotfiles-pwas.json
      continue
    fi
    SUDO install -d -m 0755 "/etc/opt/$b/policies/managed"
    SUDO install -m 0644 "$DOTFILES_DIR/config/browsers/$b-pwas.json" "/etc/opt/$b/policies/managed/dotfiles-pwas.json"
  done
  ok "Chrome/Edge PWA policies installed (apply on next browser start)"
}

netbird_service() {
  local bin="$HOME/.nix-profile/bin/netbird"
  [ -x "$bin" ] || { warn "netbird not in nix profile; skipping"; return; }
  has_systemd || { warn "no systemd; skipping netbird service"; return; }
  sed "s|@NETBIRD@|$bin|" "$DOTFILES_DIR/config/netbird/netbird.service" | SUDO tee /etc/systemd/system/netbird.service >/dev/null
  SUDO systemctl daemon-reload
  SUDO systemctl enable netbird.service
  SUDO systemctl restart netbird.service   # picks up a changed unit or a new binary after `dot switch`
  ok "netbird daemon running ($bin); first time: netbird up --management-url https://netbird.godemperordoge.org"
}

defguard_service() {
  local bin="$HOME/.nix-profile/bin/defguard-service"
  [ -x "$bin" ] || { warn "defguard-service not in nix profile (full profile); skipping"; return; }
  has_systemd || { warn "no systemd; skipping defguard service"; return; }
  # The service hands its socket to group "defguard"; the app's user must be in it (new login needed).
  getent group defguard >/dev/null || SUDO groupadd --system defguard
  if ! id -nG "$USER" | tr ' ' '\n' | grep -qx defguard && [ "$(getent group defguard | cut -d: -f3)" != "$(id -g)" ]; then
    SUDO usermod -aG defguard "$USER" && warn "added $USER to group defguard: log out and back in before using the VPN app"
  fi
  # VPN DNS goes through `resolvconf`; SteamOS only has resolvectl, which acts as resolvconf under that name.
  if ! have resolvconf && have resolvectl; then
    SUDO install -d -m 755 /var/lib/defguard-service/bin
    SUDO ln -sf "$(command -v resolvectl)" /var/lib/defguard-service/bin/resolvconf
  fi
  sed "s|@DEFGUARD_SERVICE@|$bin|" "$DOTFILES_DIR/config/defguard/defguard-service.service" | SUDO tee /etc/systemd/system/defguard-service.service >/dev/null
  SUDO systemctl daemon-reload
  SUDO systemctl enable defguard-service.service
  SUDO systemctl restart defguard-service.service   # picks up a new binary after `dot switch`
  ok "defguard service running ($bin)"
}

cmd_system() {
  local skip_pkgs=0 netbird=0 defguard=0
  for a in "$@"; do case "$a" in --no-pkgs) skip_pkgs=1;; --netbird) netbird=1;; --defguard) defguard=1;; esac; done
  if in_container; then
    netbird=0; defguard=0
  elif is_desktop; then
    netbird=1
  fi
  if ! in_container && [ "$(profile)" = full ]; then defguard=1; fi
  step "distro layer for $(os_id) (needs sudo)"
  [ $skip_pkgs = 1 ] || install_pkgs
  if is_desktop; then
    browser_policies
  fi
  [ $netbird = 1 ] && netbird_service
  [ $defguard = 1 ] && defguard_service
  # Prefer the distro's zsh: a login shell inside the Nix profile dies with the profile.
  local zsh_path=""
  for z in /usr/bin/zsh /bin/zsh; do [ -x "$z" ] && { zsh_path="$z"; break; }; done
  if [ -n "$zsh_path" ] && [ "$(getent passwd "$USER" | cut -d: -f7)" != "$zsh_path" ]; then
    grep -qx "$zsh_path" /etc/shells || echo "$zsh_path" | SUDO tee -a /etc/shells >/dev/null
    SUDO chsh -s "$zsh_path" "$USER" && ok "login shell → $zsh_path" || warn "chsh failed; bash will hand off to zsh instead"
  fi
}

# ---------------------------------------------------------------- user apps
flatpak_has() { flatpak info "$1" >/dev/null 2>&1; }

native_apps() {
  [ "$(os_id)" = fedora ] || die "native desktop apps currently require Fedora"
  source_nix || die "Nix is required for apps unavailable as Fedora RPMs (dot nix)"
  local app rpm attr entry store_path
  local failed=() skipped=()
  while read -r app; do
    entry="$(awk -F '|' -v app="$app" '$1 == app { print; exit }' "$DOTFILES_DIR/config/fedora-apps.tsv")"
    [ -n "$entry" ] || { failed+=("$app (no native mapping)"); continue; }
    IFS='|' read -r app rpm attr <<<"$entry"
    # Flatseal only manages Flatpaks; Aurynk currently has no packaged native build.
    if [ "$rpm" = - ] && [ "$attr" = - ]; then skipped+=("$app"); continue; fi
    if [ "$rpm" != - ] && SUDO dnf install -y "$rpm"; then continue; fi
    if [ "$attr" != - ]; then
      store_path="$(NIXPKGS_ALLOW_UNFREE=1 nix eval --impure --raw --inputs-from "$DOTFILES_DIR" "nixpkgs#$attr.outPath")" || { failed+=("$app"); continue; }
      if nix profile list --json | jq -e --arg path "$store_path" '[.elements[].storePaths[]] | index($path) != null' >/dev/null; then continue; fi
      NIXPKGS_ALLOW_UNFREE=1 nix profile install --impure --inputs-from "$DOTFILES_DIR" "nixpkgs#$attr" || failed+=("$app")
    else
      failed+=("$app")
    fi
  done < <(flatpak_apps)
  [ ${#skipped[@]} -eq 0 ] || warn "Native install skips Flatseal (Flatpak-only) and Aurynk (no native package): ${skipped[*]}"
  seed_xpipe
  if [ ${#failed[@]} -gt 0 ]; then warn "Native apps failed: ${failed[*]}"; return 1; fi
}

cmd_apps() {
  local native=0
  case "${1:-}" in
    --native) native=1 ;;
    "") in_container && native=1 ;;
    *) die "usage: dot apps [--native]" ;;
  esac
  if is_desktop && [ "$native" = 1 ]; then
    if [ "$(os_id)" = fedora ]; then
      native_apps
    else
      warn "Skipping container desktop apps: native installation currently supports Fedora; Flatpaks are disabled in containers"
    fi
  fi
  if is_desktop && [ "$native" = 0 ] && ! in_container && have flatpak; then
    step "Flatpaks (user scope)"
    flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo
    local missing=()
    while read -r app; do
      [ -z "$app" ] || [[ "$app" == \#* ]] && continue
      flatpak_has "$app" || missing+=("$app")
    done < <(flatpak_apps)
    # One at a time: a single failure (e.g. Chrome's extra-data step inside an
    # unprivileged container) would otherwise abort the whole batch.
    local failed=()
    for app in "${missing[@]}"; do
      flatpak install --user --noninteractive --or-update flathub "$app" || failed+=("$app")
    done
    [ ${#failed[@]} -eq 0 ] || warn "Flatpaks failed: ${failed[*]}"
    ok "Flatpaks: $(( ${#missing[@]} - ${#failed[@]} )) installed, rest already present"
    if [ "$(profile)" = full ] && flatpak_has com.google.Chrome; then
      flatpak override --user '--filesystem=~/.local/share/applications:create' \
        '--filesystem=~/.local/share/icons:create' com.google.Chrome ||
        warn "Could not configure Chrome web app permissions"
    fi
    seed_xpipe
  fi

  step "mise tools"
  if have mise; then
    mise install -y || warn "mise install had failures"
  fi

  if [ ! -x "$HOME/.local/bin/claude" ]; then
    step "Claude Code (native installer)"
    curl -fsSL https://claude.ai/install.sh | bash || warn "Claude Code install failed"
  else
    ok "Claude Code present"
  fi
}

seed_xpipe() {
  local prefs="$HOME/.xpipe/settings/preferences.json"
  [ -e "$prefs" ] && return
  mkdir -p "$(dirname "$prefs")"
  cp "$DOTFILES_DIR/config/xpipe/preferences.json" "$prefs"
  ok "XPipe set to sync from RustyRaptor/xpipe-sync (enter the GitHub token on first launch)"
}

# Rootless podman unpacks each image layer inside a user namespace. Without
# /etc/subuid and /etc/subgid ranges for this user, every pull dies in the middle
# with "potentially insufficient UIDs or GIDs available in user namespace".
subid_count() {
  local file="$1" total=0 name start count
  [ -r "$file" ] || { echo 0; return 0; }
  while IFS=: read -r name start count; do
    [ "$name" = "$(id -un)" ] || continue
    case "$count" in ''|*[!0-9]*) continue ;; esac
    total=$(( total + count ))
  done <"$file"
  echo "$total"
}

podman_subid_ok() {
  [ "$(subid_count "${SUBUID_FILE:-/etc/subuid}")" -ge 65536 ] &&
    [ "$(subid_count "${SUBGID_FILE:-/etc/subgid}")" -ge 65536 ]
}

podman_subid_hint() {
  local me; me="$(id -un)"
  warn "rootless podman has no subuid/subgid range for $me"
  warn "  ${SUBUID_FILE:-/etc/subuid} has $(subid_count "${SUBUID_FILE:-/etc/subuid}") ids, ${SUBGID_FILE:-/etc/subgid} has $(subid_count "${SUBGID_FILE:-/etc/subgid}") (65536 needed)"
  warn "  fix: sudo usermod --add-subuids 100000-165535 --add-subgids 100000-165535 $me && podman system migrate"
  warn "  last resort (deletes images/containers): podman system reset"
}

cmd_boxes() {
  if in_container; then ok "skipping distrobox inside a container"; return; fi
  have distrobox || die "distrobox missing (dot system)"
  if have podman && [ "$(id -u)" != 0 ] && ! podman_subid_ok; then podman_subid_hint; fi
  distrobox assemble create --file "$HOME/.config/distrobox/distrobox.ini"
}

# ---------------------------------------------------------------- secrets (Bitwarden)
BW_PREFIX="dotfiles"
bw_target_server() {
  if [ -n "${BW_SERVER:-}" ]; then
    printf '%s\n' "$BW_SERVER"
  elif [ "$(profile)" = full-work ]; then
    echo https://vault.etvamerica.com
  else
    echo https://vault.godemperordoge.org
  fi
}

# Bitwarden only accepts a server change when logged out.
bw_server() {
  have bw || return 0
  local target state current status
  target="$(bw_target_server)"
  state="$(bw status)" || return 1
  current="$(jq -r '.serverUrl // empty' <<<"$state")" || return 1
  status="$(jq -r '.status // empty' <<<"$state")" || return 1
  [ "${current%/}" = "${target%/}" ] && return 0
  if [ "$status" != unauthenticated ]; then
    warn "bw must be logged out before switching to $target (run: bw logout, then retry)"
    return 1
  fi
  bw --nointeraction config server "$target" </dev/null >/dev/null && ok "bw server → $target"
}

bw_ready() {
  have bw || die "bitwarden-cli missing (dot switch)"
  bw_server || die "Bitwarden server does not match the selected profile"
  local status; status="$(bw status | jq -r .status)"
  case "$status" in
    unlocked) return 0 ;;
    unauthenticated) die "run: bw login   then: export BW_SESSION=\$(bw unlock --raw)" ;;
    locked) die "run: export BW_SESSION=\$(bw unlock --raw)" ;;
  esac
}

bw_find() { bw list items --search "$1" | jq -c --arg n "$1" 'first(.[] | select(.name == $n)) // empty'; }

bw_put_note() { # name, notes-file
  local name="$1" file="$2" existing
  existing="$(bw_find "$name")"
  if [ -n "$existing" ]; then
    echo "$existing" | jq --rawfile n "$file" '.notes = $n' | bw encode | bw edit item "$(echo "$existing" | jq -r .id)" >/dev/null
  else
    bw get template item | jq --arg name "$name" --rawfile n "$file" \
      '.type = 2 | .secureNote = {type: 0} | .name = $name | .notes = $n | .login = null' \
      | bw encode | bw create item >/dev/null
  fi || return 1
  ok "bitwarden: $name"
}

bw_get_note() { bw_find "$1" | jq -r '.notes // empty'; }

SECRET_FILES="$DOTFILES_DIR/config/secret-files.txt"

# $HOME-relative paths currently matched by config/secret-files.txt.
secret_file_list() {
  (cd "$HOME" && while read -r pat; do
    [ -z "$pat" ] || [[ "$pat" == \#* ]] && continue
    for f in $pat; do [ -f "$f" ] && echo "$f"; done
  done <"$SECRET_FILES") | sort -u
}

secrets_push() {
  bw_ready; bw sync >/dev/null
  [ -s "$SECRETS_ENV" ] && bw_put_note "$BW_PREFIX/secrets.env" "$SECRETS_ENV"
  while read -r rel; do
    bw_put_note "$BW_PREFIX/file/$rel" "$HOME/$rel"
  done < <(secret_file_list)
  if [ "${1:-}" = --wireguard ] && have nmcli; then
    local tmp; tmp="$(mktemp -d)"
    while IFS=: read -r name type; do
      [ "$type" = wireguard ] || continue
      SUDO cat "/etc/NetworkManager/system-connections/$name.nmconnection" >"$tmp/$name" 2>/dev/null \
        && bw_put_note "$BW_PREFIX/wireguard/$name.nmconnection" "$tmp/$name"
    done < <(nmcli -t -f NAME,TYPE connection show)
    rm -rf "$tmp"
  fi
}

secrets_pull() {
  bw_ready; bw sync >/dev/null
  local v
  v="$(bw_get_note "$BW_PREFIX/secrets.env")"
  if [ -n "$v" ]; then (umask 077; printf '%s\n' "$v" >"$SECRETS_ENV"); ok "secrets.env"; fi
  while read -r name; do
    [ -n "$name" ] || continue
    local rel="${name#"$BW_PREFIX/file/"}" f
    f="$HOME/$rel"
    mkdir -p "$(dirname "$f")"
    (umask 077; bw_get_note "$name" >"$f")
    chmod 600 "$f"; [[ "$f" == *.pub ]] && chmod 644 "$f"
    ok "~/$rel"
  done < <(bw list items --search "$BW_PREFIX/file/" | jq -r '.[].name' | grep "^$BW_PREFIX/file/")
  chmod 700 "$HOME/.ssh" 2>/dev/null || true
  if [ "${1:-}" = --wireguard ] && have nmcli; then
    while read -r name; do
      [ -n "$name" ] || continue
      local base="${name##*/}"
      bw_get_note "$name" | SUDO install -m 600 /dev/stdin "/etc/NetworkManager/system-connections/$base"
      ok "wireguard $base"
    done < <(bw list items --search "$BW_PREFIX/wireguard/" | jq -r '.[].name' | grep "^$BW_PREFIX/wireguard/")
    SUDO nmcli connection reload
  fi
  secrets_render
}

# What's in the vault vs on this machine.
secrets_status() {
  bw_ready; bw sync >/dev/null
  local items; items="$(bw list items --search "$BW_PREFIX/" | jq -c '[.[] | select(.name | startswith("'"$BW_PREFIX"'/")) | {name, notes, date: .revisionDate}]')"
  echo "vault $(bw config server) — $(echo "$items" | jq length) dotfiles items"
  local -A want=(["$BW_PREFIX/secrets.env"]="$SECRETS_ENV")
  while read -r rel; do want["$BW_PREFIX/file/$rel"]="$HOME/$rel"; done < <(secret_file_list)
  for name in "${!want[@]}"; do
    local local_f="${want[$name]}" remote
    remote="$(echo "$items" | jq -r --arg n "$name" '.[] | select(.name == $n) | .notes')"
    if [ -z "$remote" ]; then warn "$name — only on this machine (dot secrets push)"
    elif [ "$remote" = "$(cat "$local_f")" ]; then ok "$name"
    else warn "$name — differs from vault (push to upload, pull to overwrite local)"; fi
  done
  echo "$items" | jq -r '.[].name' | while read -r name; do
    [ -n "${want[$name]:-}" ] || echo "    in vault only: $name"
  done
}

secrets_add() { # file...
  [ $# -gt 0 ] || die "usage: dot secrets add <file>..."
  for f in "$@"; do
    local abs; abs="$(readlink -f "$f")"
    [[ "$abs" == "$HOME"/* ]] || die "$f is outside \$HOME"
    local rel="${abs#"$HOME"/}"
    grep -qxF "$rel" "$SECRET_FILES" || echo "$rel" >>"$SECRET_FILES"
    bw_ready; bw_put_note "$BW_PREFIX/file/$rel" "$abs"
  done
  ok "listed in config/secret-files.txt (commit it)"
}

secrets_set() { # KEY [VALUE]
  local key="${1:-}" val="${2:-}"
  [[ "$key" =~ ^[A-Z_][A-Z0-9_]*$ ]] || die "usage: dot secrets set KEY [VALUE]   (prompts if VALUE omitted)"
  [ -n "$val" ] || { read -rsp "$key: " val; echo; }
  touch "$SECRETS_ENV"; chmod 600 "$SECRETS_ENV"
  local tmp; tmp="$(mktemp)"
  grep -v "^$key=" "$SECRETS_ENV" >"$tmp" || true
  printf '%s=%s\n' "$key" "$val" >>"$tmp"
  install -m 600 "$tmp" "$SECRETS_ENV"; rm -f "$tmp"
  ok "$key saved to secrets.env"
  bw_ready; bw_put_note "$BW_PREFIX/secrets.env" "$SECRETS_ENV"
  secrets_render
}

# Fill ${VAR} placeholders in MCP templates from secrets.env and merge them in.
secrets_render() {
  [ -s "$SECRETS_ENV" ] || { warn "no $SECRETS_ENV (dot secrets pull)"; return; }
  set -a; # shellcheck disable=SC1090
  . "$SECRETS_ENV"; set +a
  local render='walk(if type == "string" then gsub("\\$\\{(?<v>[A-Z_]+)\\}"; "\(env[.v] // "")") else . end)'

  if [ "$(profile)" != full-work ]; then
    local claude_json="$HOME/.claude.json"
    [ -f "$claude_json" ] || echo '{}' >"$claude_json"
    jq --slurpfile m <(jq "$render" "$DOTFILES_DIR/config/claude/mcp.json") '.mcpServers = ((.mcpServers // {}) + $m[0])' \
      "$claude_json" >"$claude_json.tmp" && mv "$claude_json.tmp" "$claude_json" && chmod 600 "$claude_json"
    ok "Claude MCP servers"
  fi

  mkdir -p "$HOME/.pi/agent"
  (umask 077; jq "$render" "$DOTFILES_DIR/config/pi/mcp.json" >"$HOME/.pi/agent/mcp.json")
  chmod 600 "$HOME/.pi/agent/mcp.json"
  ok "pi MCP servers"

  # Git now uses the profile's credential manager and optional unlocked vault.
  # Do not write a plaintext ~/.git-credentials or modify an existing one.
}

# Keep the secretctl snapshot out of secrets.env, which is shell-sourced.
secrets_push_secretctl() (
  [ "$#" -le 1 ] || die "usage: dot secrets push-secretctl [SOURCE]"
  have secretctl || die "secretctl is required"
  local src="${1:-${SECRETCTL_FILE:-$HOME/secrets.txt}}" keys key stage jq_bin part generation checksum
  local -a parts
  keys="$(secretctl --file "$src" list)" || die "Could not list secrets"
  [ -n "$keys" ] || die "No secrets to upload"
  jq_bin="$(command -v jq)" || die "jq is required"
  bw_ready
  bw sync >/dev/null
  umask 077
  stage="$(mktemp -d)"
  trap 'rm -rf -- "$stage"' EXIT
  generation="${stage##*/}"
  while IFS= read -r key; do
    secretctl --file "$src" get "$key" -- "$jq_bin" -jn --arg key "$key" 'env[$key]' |
      secretctl --file "$stage/store" add "$key" --allow-empty >/dev/null ||
      die "Could not export secretctl entry $key"
  done <<<"$keys"
  # Leave room for encryption overhead and split only ASCII base64 text.
  base64 -w0 "$stage/store" | split -b 6000 -d -a 6 - "$stage/part."
  parts=("$stage"/part.*)
  for part in "${parts[@]}"; do
    bw_put_note "$BW_PREFIX/secretctl/$generation/${part##*.}" "$part" ||
      die "Could not upload snapshot part"
  done
  checksum="$(sha256sum <"$stage/store")"
  jq -n --arg generation "$generation" --argjson parts "${#parts[@]}" \
    --arg sha256 "${checksum%% *}" '{version:1,generation:$generation,parts:$parts,sha256:$sha256}' >"$stage/manifest"
  # Publish the manifest last so a partial upload leaves the prior backup usable.
  bw_put_note "$BW_PREFIX/secretctl/manifest" "$stage/manifest"
)

secrets_pull_secretctl() (
  [ "$#" -le 1 ] || die "usage: dot secrets pull-secretctl [DESTINATION]"
  have secretctl || die "secretctl is required"
  local dest="${1:-${SECRETCTL_FILE:-$HOME/secrets.txt}}" stage manifest generation count checksum actual index part
  if [ -e "$dest" ] || [ -L "$dest" ]; then
    die "$dest already exists; choose a new destination"
  fi
  bw_ready
  bw sync >/dev/null
  umask 077
  stage="$(mktemp -- "$(dirname -- "$dest")/.secretctl-import.XXXXXXXX")"
  trap 'rm -f -- "$stage"' EXIT
  manifest="$(bw_find "$BW_PREFIX/secretctl/manifest")" || die "Could not look up the snapshot manifest"
  if [ -z "$manifest" ]; then
    bw_find "$BW_PREFIX/secretctl" |
      jq -je 'select(.type == 2) | .notes | select(type == "string" and length > 0)' >"$stage" ||
      die "No valid secretctl backup in this vault"
  else
    manifest="$(jq -er 'select(.type == 2) | .notes | fromjson |
      select(.version == 1 and (.generation | test("^tmp[.][a-zA-Z0-9]+$")) and
      (.parts | type == "number" and . >= 1 and . <= 1000000 and floor == .) and
      (.sha256 | test("^[a-f0-9]{64}$")))' <<<"$manifest")" ||
      die "Invalid secretctl snapshot manifest"
    generation="$(jq -r .generation <<<"$manifest")"
    count="$(jq -r .parts <<<"$manifest")"
    checksum="$(jq -r .sha256 <<<"$manifest")"
    {
      for ((index = 0; index < count; index++)); do
        printf -v part '%06d' "$index"
        bw_find "$BW_PREFIX/secretctl/$generation/$part" |
          jq -je 'select(.type == 2) | .notes | select(test("^[A-Za-z0-9+/=]+$"))' ||
          exit 1
      done
    } | base64 -d >"$stage" || die "Snapshot is missing a part or is corrupt"
    actual="$(sha256sum <"$stage")"
    [ "${actual%% *}" = "$checksum" ] || die "Snapshot integrity check failed"
  fi
  secretctl --file "$stage" check >/dev/null 2>&1 || die "Vault snapshot failed secretctl validation"
  ln -T -- "$stage" "$dest" || die "Could not create $dest without overwriting"
  ok "Secretctl file restored at $dest (0600)"
)

cmd_secrets() {
  local sub="${1:-}"; shift || true
  case "$sub" in
    push) secrets_push "$@" ;;
    pull) secrets_pull "$@" ;;
    status) secrets_status ;;
    add) secrets_add "$@" ;;
    set) secrets_set "$@" ;;
    render) secrets_render ;;
    push-secretctl) secrets_push_secretctl "$@" ;;
    pull-secretctl) secrets_pull_secretctl "$@" ;;
    *) die "usage: dot secrets status|push [--wireguard]|pull [--wireguard]|add FILE...|set KEY [VALUE]|render|push-secretctl [SOURCE]|pull-secretctl [DESTINATION]" ;;
  esac
}

# ---------------------------------------------------------------- defguard (VPN client)
# The home-lab Defguard instance. Core (API, admin UI) answers only the home network and the VPN;
# the edge (enrollment, client API, WireGuard endpoint) is public at vpn.godemperordoge.org.
DEFGUARD_URL="${DEFGUARD_URL:-https://defguard.godemperordoge.org}"
DEFGUARD_USER="${DEFGUARD_USER:-doge}"
DEFGUARD_DATA="$HOME/.local/share/net.defguard"

defguard_configured() { # does the app already have an instance?
  [ -f "$DEFGUARD_DATA/defguard.db" ] || return 1
  python3 - "$DEFGUARD_DATA/defguard.db" <<'PY' 2>/dev/null
import sqlite3, sys
c = sqlite3.connect("file:%s?mode=ro" % sys.argv[1], uri=True)
sys.exit(0 if c.execute("select count(*) from instance").fetchone()[0] else 1)
PY
}

# Preconfigure the Defguard app on this machine. Enrollment tokens are single-use and expire after
# 24 h, so the vault holds an API token instead (secrets.env DEFGUARD_API_TOKEN, created in Defguard
# under your profile -> API tokens) and this mints a fresh desktop token for each machine. The app
# reads provisioning.json on its next start while it has no instance configured.
cmd_defguard() {
  if defguard_configured && [ "${1:-}" != --force ]; then
    ok "Defguard app already has an instance (dot defguard --force to provision anyway)"; return
  fi
  [ -s "$SECRETS_ENV" ] || die "no $SECRETS_ENV (dot secrets pull)"
  local token; token="$(sed -n 's/^DEFGUARD_API_TOKEN=//p' "$SECRETS_ENV" | tail -1)"
  [ -n "$token" ] || die "no DEFGUARD_API_TOKEN: create one in Defguard (your profile -> API tokens), then: dot secrets set DEFGUARD_API_TOKEN"
  local resp
  # header via a file descriptor so the token never shows up in the process list
  resp="$(curl -fsS -m 20 -X POST -H @<(printf 'Authorization: Bearer %s\n' "$token") \
    -H 'Content-Type: application/json' -d '{"send_enrollment_notification": false}' \
    "$DEFGUARD_URL/api/v1/user/$DEFGUARD_USER/start_desktop")" \
    || die "could not get a token from $DEFGUARD_URL (it answers only the home network and the VPN; is the API token still valid?)"
  mkdir -p "$DEFGUARD_DATA"
  (umask 077; echo "$resp" | jq -e '{enrollment_token, enrollment_url}' >"$DEFGUARD_DATA/provisioning.json") \
    || die "unexpected answer from Defguard"
  ok "Defguard app preconfigured for $(echo "$resp" | jq -r .enrollment_url) (token valid 24 h)"
  if pgrep -x defguard-client >/dev/null || pgrep -f '/bin/.defguard-client-wrapped' >/dev/null; then
    warn "quit the Defguard app (tray icon -> Quit) and start it again to pick it up"
  else
    echo "    start 'Defguard' from the menu to finish (sign in with Doge Home Lab)"
  fi
}

# ---------------------------------------------------------------- wallpapers
cmd_wallpapers() {
  if [ -d "$WALLPAPER_SRC_WORK" ] || [ -d "$WALLPAPER_SRC_PERSONAL" ]; then
    have wallpaper-sort || die "wallpaper-sort missing (full profile)"
    [ -d "$WALLPAPER_SRC_WORK" ] && wallpaper-sort "$WALLPAPER_SRC_WORK" "$WALLPAPER_DIR/work"
    [ "$(profile)" != full-work ] && [ -d "$WALLPAPER_SRC_PERSONAL" ] && wallpaper-sort "$WALLPAPER_SRC_PERSONAL" "$WALLPAPER_DIR/personal"
    if [ -d "$WALLPAPER_DIR/.git" ] && [ "${1:-}" = --push ]; then
      git -C "$WALLPAPER_DIR" add -A && git -C "$WALLPAPER_DIR" commit -qm "wallpapers: resort $(date -I)" && git -C "$WALLPAPER_DIR" push -q || true
    fi
  elif [ ! -d "$WALLPAPER_DIR/.git" ]; then
    step "cloning wallpapers"
    local auth=()
    [ -n "${GITEA_TOKEN:-}" ] && auth=(-c "http.extraHeader=Authorization: token $GITEA_TOKEN")
    git "${auth[@]}" clone --depth 1 --filter=blob:none --sparse "$WALLPAPER_REPO" "$WALLPAPER_DIR" || warn "wallpaper clone failed (dot secrets pull for git credentials?)"
  else
    git -C "$WALLPAPER_DIR" pull -q --ff-only || true
  fi
  if [ -d "$WALLPAPER_DIR/.git" ]; then
    if [ "$(profile)" = full-work ]; then
      git -C "$WALLPAPER_DIR" sparse-checkout set work
    else
      git -C "$WALLPAPER_DIR" sparse-checkout disable
    fi
  fi
  have daynight-hooks && daynight-hooks --once >/dev/null 2>&1 || true
}

# ---------------------------------------------------------------- sounds
sound_output_info() {
  have wpctl || return 0
  local sink; sink="$(wpctl inspect @DEFAULT_AUDIO_SINK@ 2>/dev/null | sed -n 's/.*node.description = "\(.*\)"/\1/p' | head -1)"
  local vol; vol="$(wpctl get-volume @DEFAULT_AUDIO_SINK@ 2>/dev/null)"
  echo "output: ${sink:-?} — ${vol:-?}"
  [[ "$vol" == *MUTED* ]] && warn "default output is muted"
  wpctl status 2>/dev/null | sed -n '/Sinks:/,/Sources:/p' | grep -E "MUTED|vol: 0\.00" | sed 's/^[ │*]*/   muted sink: /'
}

# All theme/notification sounds share one "event"/Notification role stream whose
# mute + volume WirePlumber remembers. Plasma's mixer can mute it ("Notification
# Sounds"), which silences everything except the volume tick. Unmute it at 100%.
ensure_event_stream() {
  have pactl || return 0
  local state="$HOME/.local/state/wireplumber/stream-properties"
  if [ -f "$state" ] && ! grep -q 'media.role:Notification=.*"mute":true' "$state" \
     && ! grep -qE 'media.role:Notification=.*"volume":0\.[0-8]' "$state"; then
    return 0
  fi
  local f; f="$(ls "$HOME"/.local/share/sounds/portal2/stereo/bell.* 2>/dev/null | head -1)"
  [ -n "$f" ] || return 0
  paplay --property=media.role=event --property=application.name=dot-sounds "$f" & local p=$!
  local id=""
  for _ in $(seq 20); do
    id="$(pactl -f json list sink-inputs 2>/dev/null | jq -r '.[] | select(.properties["application.name"] == "dot-sounds") | .index' | head -1)"
    [ -n "$id" ] && break; sleep 0.1
  done
  if [ -n "$id" ]; then
    pactl set-sink-input-mute "$id" 0
    pactl set-sink-input-volume "$id" 100%
    ok "notification sounds stream unmuted at 100%"
  else
    warn "couldn't catch the event stream to unmute it; unmute 'Notification Sounds' in the volume applet"
  fi
  wait $p 2>/dev/null || true
}

play_event() { # freedesktop sound name
  if have canberra-gtk-play; then
    canberra-gtk-play -i "$1" -d "dot sounds test" 2>/dev/null
  else
    local f; f="$(ls "$HOME/.local/share/sounds/portal2/stereo/$1".* 2>/dev/null | head -1)"
    [ -n "$f" ] && { pw-play --media-role=Notification "$f" 2>/dev/null || paplay "$f"; }
  fi
}

cmd_sounds() {
  [ "$(profile)" != full-work ] || die "full-work uses the default KDE sound theme; Portal 2 sounds are personal-only"
  case "${1:-build}" in
    build)
      have build-sound-theme || die "build-sound-theme missing (full profile)"
      shift || true; build-sound-theme "$@"
      ensure_event_stream ;;
    test)
      # dot sounds test [event...]   — plays each theme sound with its name
      sound_output_info
      ensure_event_stream
      local events=("${@:2}")
      [ ${#events[@]} -gt 0 ] || mapfile -t events < <(ls "$HOME/.local/share/sounds/portal2/stereo" | sed 's/\.[^.]*$//' | sort)
      for e in "${events[@]}"; do printf '  ♪ %s\n' "$e"; play_event "$e"; sleep 0.4; done ;;
    notify)
      # A real desktop notification, the same path Chrome/Telegram/etc. take.
      sound_output_info
      ensure_event_stream
      notify-send -a "dot sounds" "Aperture Science" "This was a triumph. (If you heard a ding, app notifications have sound.)" ;;
    *) die "usage: dot sounds [build|test [event...]|notify]" ;;
  esac
}

# ---------------------------------------------------------------- update / doctor
# Pull the checkout and apply it: no package/tool/app upgrades, no flake input bump.
# A newly added package still gets built once here, which can take a while.
cmd_sync() {
  case " ${*:-} " in
    *" --inputs "*) die "dot sync never bumps flake inputs; use: dot update --inputs" ;;
  esac
  step "pull dotfiles"
  git -C "$DOTFILES_DIR" pull --ff-only || warn "git pull failed; continuing with local tree"
  cmd_switch "$@"
  ok "dotfiles synced (no app, tool or flake-input upgrades)"
}

cmd_update() {
  local args=() a sync_only=0
  for a in "$@"; do
    case "$a" in
      --switch-only) sync_only=1 ;;
      *) args+=("$a") ;;
    esac
  done
  if [ "$sync_only" = 1 ]; then
    step "dot update --switch-only → dot sync"
    cmd_sync ${args[@]+"${args[@]}"}
    return
  fi
  set -- ${args[@]+"${args[@]}"}
  step "pull dotfiles"
  git -C "$DOTFILES_DIR" pull --rebase --autostash || warn "git pull failed; continuing with local tree"
  if [ "${1:-}" = --inputs ]; then
    step "nix flake update"
    source_nix && ensure_nix_features && nix flake update --flake "$DOTFILES_DIR"
  fi
  cmd_switch
  is_desktop && ! in_container && have flatpak && { step "flatpak update"; flatpak update --user -y --noninteractive || true; }
  have mise && { step "mise upgrade"; mise upgrade -y || true; }
  have claude && { step "claude update"; claude update || true; }
  cmd_apps
}

# Home Manager's reloadSystemd step reports the state of the *whole* user manager
# before it reloads anything, so one failed third-party unit (a portal service on a
# display-less host) makes every switch print a wall of warnings. It never starts
# those units, and it cannot clear them. Diagnose them here, on demand.
systemd_user_report() {
  local fix="${1:-0}" state units oneline flapping u portals=() unmanaged=() path real
  has_systemd || return 0
  state="$(systemctl --user is-system-running 2>/dev/null || true)"
  printf 'user systemd: %s\n' "${state:-unknown}"
  units="$(systemctl --user --no-pager --no-legend --plain --state=failed list-units 2>/dev/null | awk 'NF{print $1}')"
  if [ -n "${units// /}" ]; then
    oneline="$(echo $units)"
    warn "failed user units (Home Manager repeats these on every switch):"
    printf '  %s\n' $units
    for u in $units; do case "$u" in xdg-desktop-portal*) portals+=("$u");; esac; done
    if [ "$fix" = 1 ]; then
      # shellcheck disable=SC2086
      systemctl --user reset-failed $units 2>/dev/null && ok "cleared failed state: $oneline"
    else
      printf '  clear the state: systemctl --user reset-failed %s\n' "$oneline"
    fi
    [ ${#portals[@]} -eq 0 ] || printf '  no display here: any app asking D-Bus for org.freedesktop.portal.Desktop starts\n  %s, which cannot open a display and times out. Masking stops the\n  retries: systemctl --user mask %s\n' "$(echo "${portals[*]}")" "$(echo "${portals[*]}")"
  fi
  flapping="$(systemctl --user --no-pager --no-legend --plain --state=activating list-units 2>/dev/null | awk '$4 == "auto-restart" {print $1}')"
  [ -z "${flapping// /}" ] || { warn "restart-looping user units (each retry writes to the journal):"; printf '  %s\n' $flapping; printf '  inspect: systemctl --user status <unit>  /  stop: systemctl --user stop <unit>\n'; }
  # Units in ~/.config/systemd/user that no home-manager generation owns. Tracked
  # files wired by hand, and one-off units written straight into the home.
  for path in "$HOME/.config/systemd/user"/*.service "$HOME/.config/systemd/user"/*.timer; do
    [ -e "$path" ] || continue
    real="$(readlink -f "$path" 2>/dev/null || true)"
    case "$real" in
      /nix/store/*) continue ;;
      "$DOTFILES_DIR"/*) unmanaged+=("$(basename "$path") [git, wired by hand]") ;;
      *) unmanaged+=("$(basename "$path") [not in dotfiles]") ;;
    esac
  done
  if [ ${#unmanaged[@]} -gt 0 ]; then
    warn "user units outside home-manager (neither 'dot switch' nor git clean-up covers these):"
    printf '  %s\n' "${unmanaged[@]}"
    printf '  move the ones you want to keep into home/<module>.nix (systemd.user.services) and delete the file\n'
  fi
}

cmd_doctor() {
  local p fix=0; [ "${1:-}" = --fix ] && fix=1
  p="$(profile)"
  printf 'os=%s profile=%s container=%s systemd=%s\n' "$(os_id)" "$p" "$(in_container && echo yes || echo no)" "$(has_systemd && echo yes || echo no)"
  chk() { if eval "$2" >/dev/null 2>&1; then ok "$1"; else warn "$1 — $3"; fi; }
  # Diagnose interrupted installs and disabled features independently, without
  # network access or automatically changing the installation.
  source "$DOTFILES_DIR/scripts/doctor-nix.sh"
  doctor_nix
  chk "home-manager" "have home-manager" "dot switch"
  chk "zsh + oh-my-zsh" "have zsh && [ -d \"\$(dirname \"\$(readlink -f ~/.zshrc)\")\" ]" "dot switch"
  chk "mise" "have mise" "dot switch"
  chk "uv" "have uv || mise which uv" "dot apps"
  chk "pi" "have pi || mise which pi" "dot apps"
  chk "pokemon-go-colorscripts" "have pokemon-go-colorscripts || mise which pokemon-go-colorscripts" "dot apps"
  [ "$p" != full ] || chk "codex" "have codex" "dot switch"
  chk "Git credential manager" "have git-credential-dotfiles && have git-credential-manager" "dot switch"
  if is_desktop; then
    chk "SourceGit" "have sourcegit" "dot switch"
    chk "Git browser OAuth helper" "have git-credential-oauth" "dot switch"
  fi
  chk "claude" "[ -x ~/.local/bin/claude ]" "dot apps"
  if ! in_container; then
    chk "podman" "have podman" "dot system"
    chk "podman subuid/subgid" "podman_subid_ok" "dot boxes explains the usermod fix"
    chk "distrobox" "have distrobox" "dot system"
  fi
  chk "ssh key" "[ -f ~/.ssh/id_ed25519 ]" "dot secrets pull"
  chk "secrets.env" "[ -s $SECRETS_ENV ]" "dot secrets pull"
  if is_desktop; then
    if ! in_container; then
    chk "flatpak" "have flatpak" "dot system"
    while read -r app; do
      [ -z "$app" ] || [[ "$app" == \#* ]] && continue
      chk "flatpak $app" "flatpak_has $app" "dot apps"
    done < <(flatpak_apps)
    fi
    [ "$p" != full ] || chk "Chrome PWA policy" "[ -f /etc/opt/chrome/policies/managed/dotfiles-pwas.json ]" "dot system"
    chk "Edge PWA policy" "[ -f /etc/opt/edge/policies/managed/dotfiles-pwas.json ]" "dot system"
    chk "wallpapers" "[ -d $WALLPAPER_DIR/work ]" "dot wallpapers"
    if has_systemd; then
      chk "konsole-daynight service" "systemctl --user is-active konsole-daynight" "dot switch, then log in to Plasma"
      chk "daynight-hooks service" "systemctl --user is-active daynight-hooks" "dot switch, then log in to Plasma"
      if ! in_container; then chk "netbird daemon" "systemctl is-active netbird" "dot system --netbird"; fi

    # Free-model handoff pipeline: a dead daemon or an off-policy lane stays invisible
    # until someone tries to delegate, so check it here.
    chk "handoff daemon" "systemctl --user is-active handoff.service" "systemctl --user start handoff"
    chk "handoff probe timer" "systemctl --user list-timers handoff-probe.timer --no-pager | grep -q handoff-probe.timer" "systemctl --user start handoff-probe.timer"
    chk "handoff pool policy" "handoff-pool-check" "edit config/free-agent/pool.json: every lane needs usage=developer-api"
    chk "handoff pool alive" "free-agent --list >/dev/null" "free-agent --list"
    else
      chk "day/night daemons (XDG autostart)" "pgrep -f daynight-hooks" "log in to Plasma"
    fi
  fi
  systemd_user_report "$fix"
}

cmd_bootstrap() {
  local sys=1; [ "${DOTFILES_SKIP_SYSTEM:-0}" = 1 ] && sys=0
  [ $sys = 1 ] && { install_pkgs || warn "distro packages incomplete; re-run: dot system"; }
  cmd_nix
  cmd_switch
  [ $sys = 1 ] && { cmd_system --no-pkgs || warn "system layer incomplete; re-run: dot system"; }
  # The new profile puts mise & friends on PATH.
  export PATH="$HOME/.nix-profile/bin:$HOME/.local/bin:$PATH"
  cmd_apps
  is_desktop && { cmd_wallpapers || true; }
  bw_server || true
  cat <<EOF

${c_grn}Done.${c_off} Next, once per machine:
  bw login && export BW_SESSION=\$(bw unlock --raw) && dot secrets pull   # SSH keys and MCP tokens
  dot boxes            # create the general/etv distroboxes
  dot doctor           # see what's left
Then sign in: Edge (work), Chrome + Firefox (personal), XPipe git sync token, Bitwarden.
EOF
}

usage() {
  cat <<'EOF'
dot — portable dev environment

  dot bootstrap            first-time setup (nix → system → switch → apps)
  dot update [--inputs]    pull repo, (bump flake inputs), switch, update flatpaks/mise/claude
  dot sync [profile]       pull repo (--ff-only) and switch only — no upgrades, no flake input bump
  dot switch [profile]     apply the home-manager config
  dot profile [full|full-work|headless|auto]
  dot system [--netbird] [--defguard]   sudo layer: distro packages, browser PWA policies, netbird, Defguard VPN service, login shell
  dot nix                  install Nix if missing
  dot apps [--native]      profile apps (native on Fedora containers), mise tools, Claude Code
  dot secrets status|push|pull|add|set|render   Bitwarden-backed tokens, keys, files, WireGuard
  dot secrets push-secretctl|pull-secretctl   Back up or restore a secretctl file
  dot defguard [--force]   preconfigure the Defguard VPN app (one-time token minted with DEFGUARD_API_TOKEN)
  dot wallpapers [--push]  sort wallpapers into light/dark (or clone them)
  dot sounds [build|test|notify]  Portal 2 sound theme: build it, play every sound, or fire a test notification
  dot boxes                create distroboxes from distrobox.ini
  dot doctor [--fix]       check what's installed; --fix clears failed user units
EOF
}

main() {
  local cmd="${1:-help}"; shift || true
  case "$cmd" in
    bootstrap|update|sync|switch|profile|system|nix|apps|secrets|defguard|wallpapers|sounds|boxes|doctor) "cmd_$cmd" "$@" ;;
    help|-h|--help) usage ;;
    *) usage; exit 1 ;;
  esac
}
main "$@"
