#!/usr/bin/env bash
# agentic-works-install — VS Code with Agentic Works on this Mac or Linux desktop, in one command:
#
#   bash agentic-works-install.sh
#
# macOS (arm64, x86_64); Ubuntu 22.04+ and Debian-based Linux; RHEL/Rocky 8 and 9; Fedora. Installs VS Code if it
# is missing and puts `code` on the PATH; uninstalls the standalone Perch, chirp, jay, kestrel and Gannet (after asking),
# which Agentic Works replaces; installs this release's Agentic Works .vsix (SHA-256 checked), its companion extensions and the
# GitHub CLI (signed in from Agentic Works' walkthrough, not here); sets VS Code's look and its activity-bar icons (on a
# VS Code never started), then opens VS Code. On Linux it does this in a VS Code of its own (its own folders, a launcher
# command and an app-launcher icon; no profile or standalone step): the user's own VS Code is not touched (note 107).
# It prints a checklist, one line per step. Each step checks first, so
# a rerun only fills in what is missing. A failed step is reported and the run goes on; the exit status is 1 when
# any step failed. Design: docs/notes/102-agentic-works-installer.md.
#
# Runs under macOS's /bin/bash 3.2: no associative arrays, mapfile, ${x,,}, |& or [[ -v ]].
# No `set -e`: each step reports its own result and the run continues.
#
# Environment:
#   NO_COLOR                 plain marks even on a terminal
#   AGENTIC_WORKS_INSTALL_FAKE_OS    test seam only: macos|ubuntu|debian|rhel|fedora instead of detecting the platform
#   AGENTIC_WORKS_INSTALL_FAKE_ARCH  test seam only: instead of `uname -m`
#   AGENTIC_WORKS_INSTALL_NO_MAIN    test seam only: 1 = define the functions and return, for tests that source this file
#   AGENTIC_WORKS_INSTALL_TTY        test seam only: the file answers are read from, one per line, instead of /dev/tty
#   AGENTIC_WORKS_INSTALL_VSIX_URL   test seam only: where Agentic Works' .vsix is downloaded from, instead of this release
#   AGENTIC_WORKS_INSTALL_APT_DIR    test seam only: instead of /etc/apt, where existing apt sources are looked for
#   AGENTIC_WORKS_INSTALL_HELPER     agentic-works-install-helper's path, instead of the one beside this script
#   AGENTIC_WORKS_INSTALL_PYTHON3    test seam only: the python3 path taken as found, instead of `command -v python3`
#   AGENTIC_WORKS_INSTALL_APPLE_PYTHON3  test seam only: the path taken for a Mac's own python3, instead of /usr/bin/python3
#   AGENTIC_WORKS_INSTALL_PLATFORM_PYTHON  test seam only: instead of /usr/libexec/platform-python (RHEL 8's system python)
#   AGENTIC_WORKS_INSTALL_GIT        test seam only: the git path taken as found, instead of `command -v git`
#   AGENTIC_WORKS_INSTALL_CLT_WAIT   seconds to wait for Apple's Command Line Tools after `xcode-select --install` (600)
#   AGENTIC_WORKS_INSTALL_CLAUDE_INSTALLER  test seam only: where Claude Code's installer is downloaded from, instead of
#                            https://claude.ai/install.sh
set -u

# Agentic Works' version and its .vsix's SHA-256: written in by `make release`. A copy without them refuses the Agentic Works step.
AGENTIC_WORKS_VERSION="1.1.22"
AGENTIC_WORKS_SHA256="c6301fc0a6a02a31c42d6b8f93162f6da52cbeddbb0a0d6e6d17bd48c29b1d52"
AGENTIC_WORKS_ID="agenticworks.agentic-works"
AGENTIC_WORKS_VSIX_URL=${AGENTIC_WORKS_INSTALL_VSIX_URL:-"https://github.com/agenticworks-cloud/agentic-works/releases/download/v$AGENTIC_WORKS_VERSION/agentic-works-$AGENTIC_WORKS_VERSION.vsix"}
LATEST_INSTALLER="https://github.com/agenticworks-cloud/agentic-works/releases/latest/download/agentic-works-install.sh"
STANDALONE="seanahn.perch seanahn.chirp seanahn.jay seanahn.kestrel-prs seanahn.gannet"  # the extensions Agentic Works replaces
COMPANIONS="anthropic.claude-code openai.chatgpt seanahn.perch-audio"  # Perch runs claude and codex through these
GH_KEY="https://cli.github.com/packages/githubcli-archive-keyring.gpg"
GH_RPM_REPO="https://cli.github.com/packages/rpm/gh-cli.repo"
APT_DIR=${AGENTIC_WORKS_INSTALL_APT_DIR:-/etc/apt}

STEP_NAMES="vscode path launcher profile standalone extension companions claude git github homebrew settings icons open"  # what --skip accepts, in run order
SUPPORTED="macOS (arm64, x86_64); Ubuntu 22.04+ and Debian-based Linux; RHEL/Rocky 8 and 9; Fedora"
MAC_CODE="/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code"
DOWNLOAD_URL="https://code.visualstudio.com/download"
HOMEBREW_INSTALLER="https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh"
CLAUDE_INSTALLER=${AGENTIC_WORKS_INSTALL_CLAUDE_INSTALLER:-"https://claude.ai/install.sh"}
MS_KEY="https://packages.microsoft.com/keys/microsoft.asc"
ORIG_PATH=$PATH  # the PATH a new terminal would have, before this run adds to it

DRY_RUN=0
YES=0
NO_OPEN=0
FOLDER=""  # --folder DIR: the folder the window opened to make --profile's profile opens on, so a setup that opens it after needs no second window
TRUST_FOLDER=0  # --trust-folder: that window opens --folder trusted (no Restricted Mode, where Agentic Works is off); the setup vouches for the folder
WINDOW_OPENED=0  # this run opened a VS Code window (to make the profile): open_vscode opens no other
WINDOW_AT=0  # $SECONDS when that window was open: the settings step writes settings.json once more, that window's settle time later
WINDOW_MARK=""  # --window-mark FILE: made when this run opened a VS Code window, so a setup run around it doesn't open another
PROFILE=""  # --profile NAME (macOS): the VS Code profile the extensions, settings and icons go into; else the user's own
NAME="Agentic Works"  # --name NAME: on Linux, whose VS Code of its own this is (its folders, launcher and icon); note 107
ICON_FILE=""  # --icon FILE: on Linux, the PNG or SVG the desktop entry shows
OWN=0  # 1 on Linux: Agentic Works' own VS Code, on the folders below; the user's own VS Code is never called
SLUG="" OWN_ROOT="" OWN_DATA="" OWN_EXT="" OWN_SHARED=""
CODEBASE_SEARCH=0  # --codebase-search: agents.codebaseIndex.enabled true in the settings step; else the walkthrough offers it
TEAMS_APP=""       # --teams-app <clientId>:<tenant>: the Teams sign-in's company app, for the settings step
SKIPS=" "
OS=""
ARCH=""
CODE="code"
CODE_DATA=""  # as root on Linux: the --user-data-dir VS Code's CLI insists on (its default, ~/.config/Code)
AS_ROOT=0
SUDO=""
TTY_OPEN=0
CLASH=""  # why Agentic Works can't go in beside the standalone five; when set, Agentic Works fails and the steps after it stay out
AGENTIC_WORKS_FRESH=0  # 1 when this run installs Agentic Works where there was none: then VS Code is opened
RELOAD_VSCODE=0  # VS Code was open while Agentic Works came or changed: say to reload its local windows
DOCK_RESTART=0  # its own VS Code runs, started by a launcher from before the dock: say to quit it and start it again
VSIX_DIR=""  # the .vsix download's temp dir while it exists; cleanup removes it on an interrupt too
INLINED_HELPER=""  # the released script's own copy of the helper, written to a private temp file at start
HOMEBREW_STATE=""  # planned (a dry run printed its install) or failed, so a second step doesn't repeat it
HOMEBREW_USED=0  # 1 once this run installed Homebrew or installed anything through it
SUDO_FAILED=0  # 1 when the up-front `sudo -v` failed: on a Mac, an account that isn't an administrator

# ---- the checklist -------------------------------------------------------------------------------------------

STEP_LABEL=""
STEP_RESULT=""
LINE_OPEN=0  # 1 while the cursor sits at the end of a terminal's "… <label>" line
SPIN_PID=""  # the spinner drawing the open line, on a terminal; stopped before anything else is printed
SPIN_PREFIX="  "  # the open line's indent: "  " for a step's own line, "      " for a waiting line under it
SPIN_TEXT=""  # the open line's text after its "…"
WAIT_OPEN=0  # 1 while the open line is a waiting line (step_wait), which step_end keeps rather than overwrites
N_OK=0
N_SKIP=0
N_FAIL=0
C_OK="" C_SKIP="" C_FAIL="" C_END=""
if [ -t 1 ] && [ -z "${NO_COLOR+set}" ]; then
  C_OK=$'\033[32m' C_SKIP=$'\033[90m' C_FAIL=$'\033[31m' C_END=$'\033[0m'
fi
LOG=/dev/null  # every command's output; made in main, kept when a step fails

step_begin() {  # $1 = label: "  … <label>", overwritten by step_end on a terminal, where a spinner turns meanwhile
  STEP_LABEL=$1
  SPIN_PREFIX="  " SPIN_TEXT=$1 WAIT_OPEN=0
  if [ -t 1 ]; then
    printf '  … %s' "$STEP_LABEL"
    LINE_OPEN=1
    spinner_start
  else
    printf '  … %s\n' "$STEP_LABEL"
  fi
}

spinner_start() {  # the "…" of the open line turns until spinner_stop; it ends by itself if this script is gone
  local parent=$$
  (
    while kill -0 "$parent" 2> /dev/null; do
      for f in ⠋ ⠙ ⠹ ⠸ ⠼ ⠴ ⠦ ⠧ ⠇ ⠏; do
        printf '\r%s%s %s' "$SPIN_PREFIX" "$f" "$SPIN_TEXT"
        sleep 0.1
      done
    done
  ) &
  SPIN_PID=$!
}

spinner_stop() {  # before anything else is printed: the spinner gone, the open line back to "  … <label>"
  [ -n "$SPIN_PID" ] || return 0
  { kill "$SPIN_PID" && wait "$SPIN_PID"; } 2> /dev/null
  SPIN_PID=""
  [ "$LINE_OPEN" = 1 ] && printf '\r%s… %s' "$SPIN_PREFIX" "$SPIN_TEXT"
  return 0
}

step_wait() {  # $1 = text: a line under the step for a long wait (an install, a download), its "…" turning until
               # the next output; without a terminal, a plain line as step_say prints
  spinner_stop
  if [ "$LINE_OPEN" = 1 ]; then
    printf '\n'
    LINE_OPEN=0
  fi
  if [ -t 1 ]; then
    SPIN_PREFIX="      " SPIN_TEXT=$1 WAIT_OPEN=1
    printf '      … %s' "$1"
    LINE_OPEN=1
    spinner_start
  else
    printf '      %s\n' "$1"
  fi
}

step_say() {  # $1 = text: a line under the step in progress (prompts, URLs, dry-run commands)
  spinner_stop
  if [ "$LINE_OPEN" = 1 ]; then
    printf '\n'
    LINE_OPEN=0 WAIT_OPEN=0
  fi
  printf '      %s\n' "$1"
}

step_end() {  # $1 = done|already|skipped|failed, $2 = detail
  local result=$1 detail=${2:-} mark colour text
  case $result in
    done|already)
      mark='✓' colour=$C_OK text=$STEP_LABEL
      [ -n "$detail" ] && text="$text ($detail)"
      [ "$result" = already ] && text="$text (already)"
      N_OK=$((N_OK + 1)) ;;
    skipped)
      mark='–' colour=$C_SKIP text="$STEP_LABEL: $detail"
      N_SKIP=$((N_SKIP + 1)) ;;
    *)
      result=failed mark='✗' colour=$C_FAIL text="$STEP_LABEL: $detail"
      N_FAIL=$((N_FAIL + 1)) ;;
  esac
  spinner_stop
  if [ "$LINE_OPEN" = 1 ]; then
    if [ "$WAIT_OPEN" = 1 ]; then printf '\n'; else printf '\r\033[K'; fi  # a waiting line stays
    LINE_OPEN=0 WAIT_OPEN=0
  fi
  printf '  %s%s%s %s\n' "$colour" "$mark" "$C_END" "$text"
  STEP_RESULT=$result
}

tally() {
  printf 'Done: %d ✓  %d –  %d ✗\n' "$N_OK" "$N_SKIP" "$N_FAIL"
}

skip_named() {  # $1 = step name: true when --skip named it
  case $SKIPS in *" $1 "*) return 0 ;; esac
  return 1
}

skipped() {  # $1 = step name, $2 = label: true (and the step is marked skipped) when --skip named it
  skip_named "$1" || return 1
  STEP_LABEL=$2
  step_end skipped "skipped (--skip $1)"
}

# ---- running commands ----------------------------------------------------------------------------------------
# Every command runs with stdin from /dev/null (the terminal's answers come from fd 3) and its output in $LOG, so
# the checklist stays readable; --dry-run prints the command under the step instead.

run() {  # argv
  if [ "$DRY_RUN" = 1 ]; then
    local shown
    shown=$(printf '%q ' "$@")
    step_say "\$ ${shown% }"
    return 0
  fi
  printf '$ %s\n' "$*" >> "$LOG"
  "$@" < /dev/null >> "$LOG" 2>&1
}

run_sh() {  # $1 = a shell command line (pipes, redirections)
  if [ "$DRY_RUN" = 1 ]; then
    step_say "\$ $1"
    return 0
  fi
  printf '$ %s\n' "$1" >> "$LOG"
  bash -o pipefail -c "$1" < /dev/null >> "$LOG" 2>&1
}

have() {  # $1 = command: on PATH
  command -v "$1" > /dev/null 2>&1
}

# ---- platform ------------------------------------------------------------------------------------------------

unsupported() {  # $1 = what this system is: the Platform step fails, and the run stops
  step_end failed "$1 isn't supported"
  printf '\nagentic-works-install supports %s.\n\n' "$SUPPORTED"
  tally
  exit 1
}

os_from_release() {  # $1 = an os-release file: prints ubuntu|debian|rhel|fedora; false on anything else
  local id like version major
  id=$(. "$1" 2> /dev/null && printf '%s' "${ID:-}")
  like=$(. "$1" 2> /dev/null && printf '%s' "${ID_LIKE:-}")
  version=$(. "$1" 2> /dev/null && printf '%s' "${VERSION_ID:-0}")
  major=${version%%.*}
  case " $id $like " in
    " ubuntu "*) [ "$major" -ge 22 ] 2> /dev/null && echo ubuntu ;;
    *" debian "*|*" ubuntu "*) echo debian ;;
    *" rhel "*) [ "$major" -ge 8 ] 2> /dev/null && echo rhel ;;
    *" fedora "*) echo fedora ;;
    *) return 1 ;;
  esac
}

detect_platform() {  # sets OS=macos|ubuntu|debian|rhel|fedora and ARCH=arm64|x86_64; exits 1 anywhere else
  local kernel machine release=/etc/os-release
  if [ -n "${AGENTIC_WORKS_INSTALL_FAKE_OS:-}" ]; then
    OS=$AGENTIC_WORKS_INSTALL_FAKE_OS
    case $OS in macos|ubuntu|debian|rhel|fedora) ;; *) unsupported "$OS" ;; esac
  else
    kernel=$(uname -s)
    case $kernel in
      Darwin) OS=macos ;;
      Linux)
        [ -r "$release" ] || unsupported "Linux without $release"
        OS=$(os_from_release "$release") ||
          unsupported "$(. "$release" 2> /dev/null && printf '%s' "${PRETTY_NAME:-${ID:-an unknown Linux}}")" ;;
      *) unsupported "$kernel" ;;
    esac
  fi
  machine=${AGENTIC_WORKS_INSTALL_FAKE_ARCH:-$(uname -m)}
  case $machine in
    arm64|aarch64) ARCH=arm64 ;;
    x86_64|amd64) ARCH=x86_64 ;;
    *) unsupported "$OS on $machine" ;;
  esac
  if [ "$(id -u)" != 0 ]; then
    SUDO=sudo
  elif [ -n "${SUDO_USER:-}" ] && [ "$SUDO_USER" != root ]; then
    # `sudo bash agentic-works-install.sh`: VS Code, its settings and the PATH block would go to root, not to this user.
    step_end failed "Run it without sudo: bash agentic-works-install.sh — it asks for your password when it needs it."
    printf '\n'
    tally
    exit 1
  else
    AS_ROOT=1
    [ "$OS" = macos ] || CODE_DATA="$HOME/.config/Code"
  fi
}

check_platform() {
  step_begin "Platform"
  detect_platform
  step_end done "$OS, $ARCH"
}

png_file() {  # $1 = a file: true when it starts as a PNG does (\x89 then PNG)
  local sig=""
  LC_ALL=C IFS= read -r -n 4 sig < "$1" 2> /dev/null
  [ "${sig#?}" = PNG ]
}

svg_file() {  # $1 = a file: true when an <svg element starts anywhere in it (as near to "an SVG" as a grep can tell)
  LC_ALL=C grep -Eq '<svg([[:space:]/>]|$)' "$1" 2> /dev/null
}

slug_of() {  # $1 = a name: lowercase, each run of other characters than a-z and 0-9 one dash, none at either end
  local in out="" c dash=0
  in=$(printf '%s' "$1" | tr 'A-Z' 'a-z')
  while [ -n "$in" ]; do
    c=${in%"${in#?}"}; in=${in#?}
    case $c in
      [a-z0-9]) [ "$dash" = 1 ] && [ -n "$out" ] && out="$out-"; out="$out$c"; dash=0 ;;
      *) dash=1 ;;
    esac
  done
  printf '%s\n' "$out"
}

set_own_folders() {  # on Linux: Agentic Works' own VS Code's folders, for NAME (note 107); --profile is refused there
  [ "$OS" = macos ] && return 0
  if [ -n "$PROFILE" ]; then
    printf 'agentic-works-install: --profile is gone on Linux: Agentic Works has a VS Code of its own; update the command that ran this\n' >&2
    exit 2
  fi
  OWN=1
  SLUG=$(slug_of "$NAME")
  OWN_ROOT="$OWN_HOME/$SLUG"
  OWN_DATA="$OWN_ROOT/data" OWN_EXT="$OWN_ROOT/extensions" OWN_SHARED="$OWN_ROOT/shared"
  CODE_DATA=""  # as root too: the own folders are what VS Code's CLI is given
  [ "$DRY_RUN" = 1 ] || mkdir -p "$OWN_DATA" "$OWN_EXT" "$OWN_SHARED"
}

# ---- VS Code -------------------------------------------------------------------------------------------------

is_cursor() {  # true when $1, or what it links to, lives in a Cursor folder: Cursor can install a `code` that opens Cursor
  local resolved
  resolved=$(readlink -f "$1" 2> /dev/null) || resolved=$1
  case "$(printf '%s %s' "$1" "$resolved" | tr '[:upper:]' '[:lower:]')" in */cursor*) return 0 ;; esac
  return 1
}

CURSOR_CODE=""  # a `code` on the PATH that opens Cursor, passed over
OWN_HOME="${XDG_DATA_HOME:-$HOME/.local/share}/agentic-works"  # every name's own VS Code is in a folder in it (note 107)

is_own_code() {  # $1 = a `code`: true when it is an Agentic Works VS Code's <root>/bin/code, never VS Code itself
  local r
  r=$(readlink -f "$1" 2> /dev/null) || r=$1
  case "$1" in "$OWN_HOME"/*/bin/code) return 0 ;; esac
  case "$r" in "$OWN_HOME"/*/bin/code) return 0 ;; esac
  return 1
}

find_code() {  # sets CODE to VS Code's CLI; false when VS Code isn't installed. A Cursor `code` is never taken for it.
  local c found=""
  CURSOR_CODE=""
  while IFS= read -r c; do
    [ -n "$c" ] || continue
    if is_cursor "$c"; then [ -n "$CURSOR_CODE" ] || CURSOR_CODE=$c; continue; fi
    is_own_code "$c" && continue  # an Agentic Works VS Code's own terminal: its bin/code runs a launcher, not VS Code
    found=$c; break
  done <<EOF_CODE
$(type -ap code 2> /dev/null)
EOF_CODE
  if [ -n "$found" ]; then
    CODE=$found
  elif [ "$OS" = macos ] && [ -x "$MAC_CODE" ]; then
    CODE=$MAC_CODE
  else
    CODE=code
    return 1
  fi
}

find_brew() {  # true when Homebrew is installed; puts it on PATH for this run
  local prefix
  command -v brew > /dev/null 2>&1 && return 0
  for prefix in /opt/homebrew /usr/local; do
    if [ -x "$prefix/bin/brew" ]; then
      PATH="$prefix/bin:$PATH"
      return 0
    fi
  done
  return 1
}

brew_bin() {  # where Homebrew's brew is, or would be after the install
  if command -v brew > /dev/null 2>&1; then
    command -v brew
  elif [ "$ARCH" = arm64 ]; then
    echo /opt/homebrew/bin/brew
  else
    echo /usr/local/bin/brew
  fi
}

SUDO_KEEPALIVE=""  # the pid of the loop keeping sudo's timestamp fresh while Homebrew installs

sudo_keepalive_start() {  # Homebrew's installer runs sudo itself, and can take longer than sudo's 5-minute timestamp
  [ -n "$SUDO" ] && [ "$DRY_RUN" != 1 ] && [ "$SUDO_FAILED" = 0 ] || return 0
  # shellcheck disable=SC2016
  ( s=""
    trap 'kill "$s" 2> /dev/null; exit 0' TERM
    while sudo -n -v 2> /dev/null; do sleep 50 & s=$!; wait "$s"; done ) < /dev/null > /dev/null 2>&1 &
  SUDO_KEEPALIVE=$!
}

sudo_keepalive_stop() {  # the loop, and its sleep
  [ -n "$SUDO_KEEPALIVE" ] || return 0
  kill "$SUDO_KEEPALIVE" 2> /dev/null
  wait "$SUDO_KEEPALIVE" 2> /dev/null
  SUDO_KEEPALIVE=""
}

ensure_homebrew() {  # macOS: Homebrew, from its own installer (which needs an administrator account)
  local tmp rc
  find_brew && return 0
  case $HOMEBREW_STATE in planned) return 0 ;; failed) return 1 ;; esac
  step_wait "Homebrew is missing; installing it first (a few minutes)"
  tmp=$(mktemp "${TMPDIR:-/tmp}/agentic-works-install-homebrew.XXXXXX") || return 1
  sudo_keepalive_start
  # Downloaded first, then run: a failed download stops here rather than running an empty script.
  run curl -fsSL -o "$tmp" "$HOMEBREW_INSTALLER" && run env NONINTERACTIVE=1 /bin/bash "$tmp"
  rc=$?
  sudo_keepalive_stop
  rm -f "$tmp"
  if [ "$DRY_RUN" = 1 ]; then
    HOMEBREW_STATE=planned
  elif [ "$rc" != 0 ] || ! find_brew; then
    HOMEBREW_STATE=failed
    return 1
  fi
  HOMEBREW_USED=1
}

homebrew_failure() {  # why ensure_homebrew failed, for a step's line
  if [ "$SUDO_FAILED" = 1 ]; then echo "needs an administrator account"; else echo "couldn't be installed"; fi
}

deb_arch() {
  if [ "$ARCH" = arm64 ]; then echo arm64; else echo amd64; fi
}

apt_has_source() {  # $1 = a repository URL: true when an apt source, not commented out, already points at it
  # As VS Code's own postinst checks: a second source for the same repository with another keyring makes every
  # apt-get fail ("Conflicting values set for option Signed-By").
  local file
  for file in "$APT_DIR/sources.list" "$APT_DIR"/sources.list.d/*.list "$APT_DIR"/sources.list.d/*.sources; do
    [ -f "$file" ] || continue
    grep -v '^[[:space:]]*#' "$file" 2> /dev/null | grep -qF "$1" && return 0
  done
  return 1
}

add_apt_repo() {  # $1 = key URL, $2 = keyring path, $3 = sources.list.d file, $4 = deb line, $5 = armored|binary
  # The sources.list line is written only once the keyring is in place and non-empty: a line without its key
  # makes every later apt-get update fail, on every rerun.
  local tmp
  tmp=$(mktemp "${TMPDIR:-/tmp}/agentic-works-install-key.XXXXXX") || return 1
  if ! run curl -fsSL -o "$tmp" "$1" || { [ "$DRY_RUN" != 1 ] && [ ! -s "$tmp" ]; }; then
    rm -f "$tmp"
    return 1
  fi
  if [ "$5" = armored ]; then
    if ! run gpg --batch --yes --dearmor -o "$tmp.gpg" "$tmp" || { [ "$DRY_RUN" != 1 ] && [ ! -s "$tmp.gpg" ]; }; then
      rm -f "$tmp" "$tmp.gpg"
      return 1
    fi
    [ "$DRY_RUN" = 1 ] || mv -f "$tmp.gpg" "$tmp"
  fi
  # shellcheck disable=SC2086
  run $SUDO install -m 644 "$tmp" "$2" || { rm -f "$tmp"; return 1; }
  rm -f "$tmp"
  run_sh "echo '$4' | $SUDO tee $3 > /dev/null"
}

PREREQS_PLANNED=" "  # a dry run's curl and gpg, printed once and then taken as installed

apt_prereqs() {  # $* = commands needed: installs the missing ones' packages (curl, gpg)
  local need="" tool
  for tool in "$@"; do
    have "$tool" && continue
    case $PREREQS_PLANNED in *" $tool "*) continue ;; esac
    [ "$DRY_RUN" = 1 ] && PREREQS_PLANNED="$PREREQS_PLANNED$tool "
    case $tool in curl) need="${need:+$need }curl ca-certificates" ;; gpg) need="${need:+$need }gnupg" ;; esac
  done
  [ -n "$need" ] || return 0  # neither is in a minimal Debian or Ubuntu
  # shellcheck disable=SC2086
  run $SUDO apt-get update && run $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y $need
}

install_vscode_apt() {  # Ubuntu and Debian-based: Microsoft's apt repository (unless a source has it); curl, gnupg
  # shellcheck disable=SC2086
  if ! apt_has_source "packages.microsoft.com/repos/code"; then
    apt_prereqs curl gpg &&
      add_apt_repo "$MS_KEY" /usr/share/keyrings/microsoft.gpg /etc/apt/sources.list.d/vscode.list \
        "deb [arch=$(deb_arch) signed-by=/usr/share/keyrings/microsoft.gpg] https://packages.microsoft.com/repos/code stable main" \
        armored || return 1
  fi
  # shellcheck disable=SC2086
  run $SUDO apt-get update && run $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y code
}

install_vscode_dnf() {  # RHEL/Rocky and Fedora: Microsoft's yum repository, with dnf
  # shellcheck disable=SC2086
  run $SUDO rpm --import "$MS_KEY" &&
    run_sh "printf '[code]\\nname=Visual Studio Code\\nbaseurl=https://packages.microsoft.com/yumrepos/vscode\\nenabled=1\\ngpgcheck=1\\ngpgkey=$MS_KEY\\n' | $SUDO tee /etc/yum.repos.d/vscode.repo > /dev/null" &&
    run $SUDO dnf install -y code
}

FEDORA_SSL="libssl.so.3()(64bit)"
SSL_FAILED=""

fedora_needs_ssl() {  # true on a Fedora without libssl.so.3 (Fedora 45 ships OpenSSL 4)
  # VS Code checks each Marketplace extension's signature with vsce-sign, a .NET program that loads libssl.so.3
  # (or .1.1) and aborts without one ("Signature verification failed with 'UnknownError'"); VS Code's rpm doesn't
  # require it.
  [ "$OS" = fedora ] || return 1
  printf '$ rpm -q --whatprovides %s\n' "$FEDORA_SSL" >> "$LOG"
  ! rpm -q --whatprovides "$FEDORA_SSL" < /dev/null >> "$LOG" 2>&1
}

install_fedora_ssl() {  # sets SSL_FAILED, the step's detail, when it fails
  SSL_FAILED="libssl.so.3 couldn't be installed, and without it VS Code installs no extensions; see $LOG, or run"
  SSL_FAILED="$SSL_FAILED \`dnf install openssl3-libs\`"
  # shellcheck disable=SC2086
  run $SUDO dnf install -y "$FEDORA_SSL"
}

ensure_vscode() {
  skipped vscode "VS Code" && return 0
  step_begin "VS Code"
  find_code; [ -z "$CURSOR_CODE" ] || step_say "The code command on your PATH opens Cursor; Agentic Works uses VS Code's own."
  if find_code; then
    if ! fedora_needs_ssl; then
      step_end already
    elif install_fedora_ssl; then
      step_end done "installed OpenSSL 3, for VS Code's extension signature checks"
    else
      step_end failed "$SSL_FAILED"
    fi
    return 0
  fi
  case $OS in
    macos)
      if ! ensure_homebrew; then
        step_end failed "Homebrew $(homebrew_failure); see $LOG, or download VS Code from $DOWNLOAD_URL"
        return 0
      fi
      HOMEBREW_USED=1
      # Homebrew's cask links VS Code's `code` into Homebrew's bin folder. Not where `code` opens Cursor (1.1.14): the
      # link could come before Cursor's on the PATH, and where Cursor's is in that folder already (an Intel Mac has
      # /usr/local/bin for both) Homebrew stops at it, "It seems there is already a Binary", and takes VS Code out again
      if [ -n "$CURSOR_CODE" ]; then
        run "$(brew_bin)" install --cask --no-binaries visual-studio-code
      else
        run "$(brew_bin)" install --cask visual-studio-code
      fi ;;
    ubuntu|debian) install_vscode_apt ;;
    rhel|fedora) install_vscode_dnf ;;
  esac
  if [ "$DRY_RUN" = 1 ]; then
    ! fedora_needs_ssl || install_fedora_ssl
    step_end done "dry run"
  elif find_code; then
    if ! fedora_needs_ssl; then
      step_end done "installed"
    elif install_fedora_ssl; then
      step_end done "installed, with OpenSSL 3 for VS Code's extension signature checks"
    else
      step_end failed "installed, but $SSL_FAILED"
    fi
  elif [ "$OS" = macos ]; then
    step_end failed "the install didn't give a 'code' command; see $LOG, or download VS Code from $DOWNLOAD_URL"
  else
    step_end failed "the install didn't give a 'code' command; see $LOG"
  fi
}

# ---- code on the PATH ----------------------------------------------------------------------------------------

PATH_MARK="# added by agentic-works-install"
PATH_END="# end agentic-works-install"

shell_profile() {  # the login shell's profile file
  case ${SHELL:-} in
    *zsh) echo "$HOME/.zprofile" ;;
    *) if [ -f "$HOME/.bash_profile" ]; then echo "$HOME/.bash_profile"; else echo "$HOME/.profile"; fi ;;
  esac
}

ensure_path() {  # `code` on PATH for this run and, through one marked block in the login profile, new terminals
  local label="code on the PATH" profile short dir brew lines
  skipped path "$label" && return 0
  step_begin "$label"
  # `code` opens Cursor, as the PATH stands (1.1.14): it is left to, for this run and for new terminals, and the line
  # says so on every run. Nothing here needs VS Code's on the PATH: it is run by its full path ($CODE)
  find_code
  if [ -n "$CURSOR_CODE" ]; then
    step_end skipped "your code command opens Cursor; left as it is"
    return 0
  fi
  profile=$(shell_profile)
  short=${profile#"$HOME"/}
  if [ -f "$profile" ] && grep -qxF "$PATH_MARK" "$profile"; then
    step_end already "$short"
    return 0
  fi
  if ! find_code; then
    if [ "$DRY_RUN" = 1 ]; then step_end done "dry run"; else step_end skipped "VS Code isn't installed"; fi
    return 0
  fi
  dir=$(dirname "$CODE")
  case ":$PATH:" in *":$dir:"*) ;; *) PATH="$dir:$PATH" ;; esac
  case ":$ORIG_PATH:" in *":$dir:"*) step_end already; return 0 ;; esac
  brew=$(brew_bin)
  if [ "$OS" = macos ] && [ "$dir" = "$(dirname "$brew")" ]; then  # Homebrew's cask: its bin dir, as it advises
    if [ -f "$profile" ] && grep -q 'brew shellenv' "$profile"; then
      step_end already "$short"
      return 0
    fi
    lines="[ -x $brew ] && eval \"\$($brew shellenv)\""
  else
    lines="case \":\$PATH:\" in *\":$dir:\"*) ;; *) export PATH=\"$dir:\$PATH\" ;; esac"
  fi
  if [ "$DRY_RUN" = 1 ]; then
    step_say "\$ append to $profile:"
    step_say "$lines"
    step_end done "dry run"
    return 0
  fi
  if printf '\n%s\n%s\n%s\n' "$PATH_MARK" "$lines" "$PATH_END" >> "$profile"; then
    step_end done "$short"
  else
    step_end failed "couldn't write $profile"
  fi
}

# ---- --profile: a VS Code profile of its own -------------------------------------------------------------------

profile_name_ok() {  # $1 = a profile name: letters, digits, spaces, dots, dashes and underscores; 1-40, not starting with a space
  [[ $1 =~ ^[A-Za-z0-9._-][A-Za-z0-9\ ._-]{0,39}$ ]]
}

ensure_profile() {  # --profile's VS Code profile, before any extension goes in: a failure stops the run, so nothing lands
  # in the user's own profile. VS Code closed: the helper makes it, with the user's settings, keybindings and snippets
  # copied in. VS Code open: it would lose a profile written beside it (tried, 2026-11-27), so a window opened on the
  # name makes it, and the helper, waiting beside that window, puts the user's settings and the look in as it does
  local label="Profile $PROFILE" rc out code_pid limit=${AGENTIC_WORKS_INSTALL_PROFILE_WAIT:-30}
  local -a window=() fill=(--fill)
  case $limit in ''|*[!0-9]*) limit=30 ;; esac
  [ -n "$PROFILE" ] || return 0
  skipped profile "$label" && return 0
  step_begin "$label"
  # A Mac's own python3 is a placeholder until Apple's Command Line Tools are there, and this step comes before git's,
  # which asks for them: on a Mac with VS Code and neither Homebrew nor the tools the run stopped here (2026-11-28)
  if ! python_ok && ! python_with_apples_tools; then
    CLASH="there is no VS Code profile $PROFILE to install into ($PYTHON_WHY)"
    step_end failed "$PYTHON_WHY"
    return 0
  fi
  run_helper vscode-profile "$PROFILE"
  rc=$?
  if [ "$DRY_RUN" = 1 ]; then step_end done "dry run"; return 0; fi
  case $rc in
    0) if [ "$HELPER_OUT" = "already set" ]; then step_end already; else step_end done "$HELPER_OUT"; fi
       return 0 ;;
    2) ;;
    *) CLASH="there is no VS Code profile $PROFILE to install into; see $LOG"
       step_end failed "couldn't make it; see $LOG"
       return 0 ;;
  esac
  # VS Code's first-launch welcome, a Copilot sign-in, is off in the user's own settings, the one place VS Code reads it
  run_helper vscode-no-onboarding || true
  # Two options for this window: --skip-welcome, none of VS Code's own walkthroughs; and --disable-workspace-trust, no
  # Restricted Mode on the folder, where Agentic Works is off and Get started can't show (VS Code, running, reads no
  # trust written beside it, and the setup vouches for the folder). A VS Code that runs takes them for this window
  # alone; one being started would take them for its own window and every window opened from inside it, until it quits
  # (a window a later `code` call opens gets that call's). The helper said "running" above from code.lock, which
  # outlives a VS Code that crashed, and says nothing of which `code` reaches the one alive (the `code` of an update on
  # disk starts a second). So they are given only when vscode-running, asked last, finds a VS Code answering where this
  # `code`, of this version, will look for one: VS Code's own test for handing the call over
  if code_version && run_helper vscode-running --code-version "$CODE_VERSION"; then
    window=(--skip-welcome)
    [ -z "$FOLDER" ] || [ "$TRUST_FOLDER" != 1 ] || window+=(--disable-workspace-trust)
  fi
  printf '$ %s%s --profile %s --new-window %s\n' "$CODE" "${window[*]+ ${window[*]}}" "$PROFILE" "$FOLDER" >> "$LOG"
  # The window reads its profile's settings.json about half a second after this, half a second before `code` returns,
  # and misses one written later until it is written again (VS Code 1.129, 2026-11-28). So `code` runs behind, and the
  # helper beside it puts the settings in the moment VS Code makes the profile's folder: the window starts with the
  # look. Should it be late, apply_settings writes the file once more
  code_cmd ${window[@]+"${window[@]}"} --new-window ${FOLDER:+"$FOLDER"} >> "$LOG" 2>&1 &
  code_pid=$!
  WINDOW_OPENED=1
  [ -z "$WINDOW_MARK" ] || : > "$WINDOW_MARK" 2>> "$LOG"
  skip_named settings || fill+=(--look)  # --skip settings: none of the look's settings, here either
  run_helper vscode-profile "$PROFILE" "${fill[@]}" --wait "$limit"
  rc=$?
  out=$HELPER_OUT
  wait "$code_pid" 2> /dev/null
  WINDOW_AT=$SECONDS
  # a profile that is there with nothing copied in is still the profile: only one that isn't stops the run
  if [ "$rc" != 0 ] && ! run_helper vscode-profile "$PROFILE"; then
    CLASH="there is no VS Code profile $PROFILE to install into; quit VS Code and rerun"
    step_end failed "VS Code didn't make it in the window opened on it; quit VS Code and rerun"
    return 0
  fi
  local on=""
  [ -z "$FOLDER" ] || on="; on $FOLDER"
  if [ "$rc" = 0 ] && [ "$out" = filled ]; then
    step_end done "made in a window VS Code opened on it, with your settings$on"
  else
    step_end done "made in a window VS Code opened on it$on"
  fi
}

# ---- the extensions: the standalone five, Agentic Works, its companions ---------------------------------------------

CODE_VERSION=""  # what this run's `code` says its version is, 1.129.1 say (code_version)
code_version() {  # sets CODE_VERSION; false when `code` says none. `code --version` starts no VS Code
  local first=""
  CODE_VERSION=""
  printf '$ %s --version\n' "$CODE" >> "$LOG"
  IFS= read -r first <<EOF_VERSION
$(code_cmd --version 2>> "$LOG")
EOF_VERSION
  printf '%s\n' "$first" >> "$LOG"
  case $first in ''|*[!0-9.]*) return 1 ;; esac
  CODE_VERSION=$first
}

code_argv() {  # CODE_ARGV = VS Code's CLI, the one way it is run: on Linux on Agentic Works' own folders (note 107); on
  # macOS in --profile's profile, and as root with the --user-data-dir it insists on
  if [ "$OWN" = 1 ]; then
    CODE_ARGV=("$CODE" --user-data-dir "$OWN_DATA" --extensions-dir "$OWN_EXT" --shared-data-dir "$OWN_SHARED")
  else
    CODE_ARGV=("$CODE" ${CODE_DATA:+--user-data-dir "$CODE_DATA"} ${PROFILE:+--profile "$PROFILE"})
  fi
}

code_cmd() {  # VS Code's CLI with CODE_ARGV's options, stdin closed
  code_argv
  "${CODE_ARGV[@]}" "$@" < /dev/null
}

code_cli() {  # code_cmd, logged and dry-run aware
  code_argv
  run "${CODE_ARGV[@]}" "$@"
}

installed_extensions() {  # the installed extensions, as lowercase id@version words
  printf '$ %s --list-extensions --show-versions\n' "$CODE" >> "$LOG"
  code_cmd --list-extensions --show-versions 2>> "$LOG" |
    tr 'A-Z' 'a-z'
}

installed_version() {  # $1 = id, $2 = installed_extensions' words: prints its version; false when not installed
  local word
  for word in $2; do
    case $word in "$1@"*) printf '%s' "${word#*@}"; return 0 ;; esac
  done
  return 1
}

version_cmp() {  # $1, $2 = versions (1.2.3): prints lt, eq or gt, numeric by field; a prerelease (-beta.1) is cut
  local a=${1%%-*} b=${2%%-*} x y
  while [ -n "$a" ] || [ -n "$b" ]; do
    x=${a%%.*} y=${b%%.*}
    if [ "$x" = "$a" ]; then a=""; else a=${a#*.}; fi
    if [ "$y" = "$b" ]; then b=""; else b=${b#*.}; fi
    x=${x%%[!0-9]*} y=${y%%[!0-9]*}
    x=$((10#${x:-0})) y=$((10#${y:-0}))
    if [ "$x" -lt "$y" ]; then echo lt; return 0; fi
    if [ "$x" -gt "$y" ]; then echo gt; return 0; fi
  done
  echo eq
}

extension_name() {  # $1 = id of one of the standalone five: its name
  case $1 in
    seanahn.perch) echo Perch ;;
    seanahn.chirp) echo chirp ;;
    seanahn.jay) echo jay ;;
    seanahn.kestrel-prs) echo kestrel ;;
    seanahn.gannet) echo Gannet ;;
    *) echo "$1" ;;
  esac
}

names_of() {  # $* = ids: their names as "A", "A and B" or "A, B and C"
  local id i=0 out=""
  for id in "$@"; do
    i=$((i + 1))
    if [ "$i" = 1 ]; then
      out=$(extension_name "$id")
    elif [ "$i" = $# ]; then
      out="$out and $(extension_name "$id")"
    else
      out="$out, $(extension_name "$id")"
    fi
  done
  printf '%s' "$out"
}

commas() {  # $* = words: "a, b, c"
  local text="$*"
  printf '%s' "${text// /, }"
}

ask_yn() {  # $1 = a [Y/n] question, on the terminal: 0 = yes (Enter too), 1 = no, 2 = no terminal or no answer
  local answer=""
  [ "$TTY_OPEN" = 1 ] || return 2
  spinner_stop
  if [ "$LINE_OPEN" = 1 ]; then
    printf '\n'
    LINE_OPEN=0
  fi
  printf '      %s ' "$1"
  if ! IFS= read -r answer <&3 && [ -z "$answer" ]; then  # end of input
    printf '\n'
    return 2
  fi
  [ -t 1 ] || printf '\n'  # on a terminal, its echo of Enter ends the line
  answer=${answer%$'\r'}
  case $answer in
    ""|[Yy]|[Yy][Ee][Ss]) return 0 ;;
    *) return 1 ;;
  esac
}

keep_gannet_state() {  # VS Code deletes an extension's global storage on uninstall: Gannet's machine.json (its folders
  # and checkouts) goes to Agentic Works' Repos part first, unless Agentic Works already has one
  local user from to
  if [ "$OS" = macos ]; then user="$HOME/Library/Application Support/Code/User"; else user="${CODE_DATA:-${XDG_CONFIG_HOME:-$HOME/.config}/Code}/User"; fi
  from="$user/globalStorage/seanahn.gannet/machine.json"
  to="$user/globalStorage/agenticworks.agentic-works/machine.json"
  [ -f "$from" ] && [ ! -e "$to" ] || return 0
  mkdir -p "${to%/*}" && cat "$from" > "$to.tmp" && mv "$to.tmp" "$to" || { rm -f "$to.tmp"; printf "couldn't keep Gannet's machine.json\n" >> "$LOG"; }
  return 0
}

own_running() {  # on Linux: true while Agentic Works' own VS Code runs (the helper finds its instance on OWN_DATA)
  python_ok && code_version && run_helper vscode-running --code-version "$CODE_VERSION"
}

vscode_open() {  # true while VS Code's app runs here: a local window or a Remote one, which can't be told apart here.
  # On Linux only Agentic Works' own VS Code matters; the user's own is never looked at (note 107)
  if [ "$OWN" = 1 ]; then own_running; return; fi
  have pgrep || return 1
  case $OS in
    macos) pgrep -f '/Visual Studio Code.app/Contents/MacOS/' > /dev/null 2>&1 ;;
    *) pgrep -x code > /dev/null 2>&1 ;;
  esac
}

ask_vscode_closed() {  # before the standalone extensions go: open local windows run them beside Agentic Works until
  # reloaded. Asked once; a Remote window runs its extensions on its host, so it may stay open and the run goes on
  local answer
  [ "$DRY_RUN" = 1 ] && return 0
  vscode_open || return 0
  if [ "$TTY_OPEN" = 1 ] && [ "$YES" != 1 ]; then
    spinner_stop
    if [ "$LINE_OPEN" = 1 ]; then printf '\n'; LINE_OPEN=0; fi
    printf '      %s ' "VS Code is open on this computer. Close its local windows (a Remote window can stay), then press Enter."
    if IFS= read -r answer <&3; then [ -t 1 ] || printf '\n'; else printf '\n'; fi
  fi
  vscode_open && RELOAD_VSCODE=1
  return 0
}

check_standalone() {  # the standalone five would clash with Agentic Works (the same command ids): uninstall them, or stop
  local installed id found="" failed="" names rc
  [ "$OWN" = 1 ] && return 0  # on Linux Agentic Works' own extensions folder has none of them (note 107)
  skipped standalone "Standalone extensions" && return 0
  find_code || return 0  # no VS Code, no extensions
  installed=$(installed_extensions)
  for id in $STANDALONE; do
    installed_version "$id" "$installed" > /dev/null && found="$found $id"
  done
  [ -n "$found" ] || return 0
  # shellcheck disable=SC2086
  names=$(names_of $found)
  if [ "$DRY_RUN" = 1 ]; then
    step_begin "Standalone extensions"
    step_say "Agentic Works replaces $names: asks to uninstall them (or --yes)"
    for id in $found; do code_cli --uninstall-extension "$id"; done
    step_end done "dry run"
    return 0
  fi
  if [ "$YES" = 1 ]; then
    rc=0
  else
    ask_yn "Agentic Works replaces $names. Uninstall them and use Agentic Works? [Y/n]"
    rc=$?
  fi
  case $rc in
    1) CLASH="stopped — Agentic Works would clash with $names; uninstall them, or rerun and answer Y"; return 0 ;;
    2) CLASH="$names would clash with Agentic Works, and there is no terminal to ask on; rerun with --yes to uninstall them"
       return 0 ;;
  esac
  ask_vscode_closed
  case " $found " in *" seanahn.gannet "*) keep_gannet_state ;; esac
  for id in $found; do
    code_cli --uninstall-extension "$id" || failed="$failed $id"
  done
  if [ -n "$failed" ]; then
    # shellcheck disable=SC2086
    CLASH="couldn't uninstall $(names_of $failed), and Agentic Works would clash with it; see $LOG,"
    CLASH="$CLASH uninstall it in VS Code, then rerun"
    return 0
  fi
  step_begin "Standalone extensions"
  step_end done "uninstalled $names"
}

agentic_works_stamped() {  # true when make release wrote this script's Agentic Works version and SHA-256 in
  case $AGENTIC_WORKS_VERSION$AGENTIC_WORKS_SHA256 in *@*) return 1 ;; esac
  [ -n "$AGENTIC_WORKS_VERSION" ] && [ -n "$AGENTIC_WORKS_SHA256" ]
}

lower() {  # $1 = text: in lowercase
  printf '%s' "$1" | tr 'A-Z' 'a-z'
}

file_sha256() {  # $1 = file: prints its SHA-256; false when neither sha256sum nor shasum is here
  local out
  if have sha256sum; then
    out=$(sha256sum "$1" 2>> "$LOG") || return 1
  elif have shasum; then
    out=$(shasum -a 256 "$1" 2>> "$LOG") || return 1
  else
    return 1
  fi
  printf '%s' "${out%% *}"
}

install_agentic_works_vsix() {  # $1 = temp dir: download this release's .vsix there, check it, install it; sets AGENTIC_WORKS_ERROR
  local vsix="$1/agentic-works-$AGENTIC_WORKS_VERSION.vsix" sum  # code installs a path only when it ends in .vsix
  AGENTIC_WORKS_ERROR=""
  if [ "$DRY_RUN" != 1 ] && ! have curl; then
    AGENTIC_WORKS_ERROR="curl isn't installed, to download $AGENTIC_WORKS_VSIX_URL"
  elif ! run curl -fsSL -o "$vsix" "$AGENTIC_WORKS_VSIX_URL"; then
    AGENTIC_WORKS_ERROR="couldn't download $AGENTIC_WORKS_VSIX_URL; check the network, then run the installer again"
  elif [ "$DRY_RUN" = 1 ]; then
    code_cli --install-extension "$vsix"
  elif ! sum=$(file_sha256 "$vsix"); then
    AGENTIC_WORKS_ERROR="no sha256sum or shasum to check the download with"
  elif [ "$(lower "$sum")" != "$(lower "$AGENTIC_WORKS_SHA256")" ]; then
    AGENTIC_WORKS_ERROR="the download did not match its checksum — run the installer again"
  elif ! code_cli --install-extension "$vsix"; then
    # Agentic Works' extension pack is its companions, which VS Code fetches from the Marketplace as it installs Agentic Works.
    AGENTIC_WORKS_ERROR="VS Code couldn't install it; it also fetches Claude Code, ChatGPT and Perch's audio from the"
    AGENTIC_WORKS_ERROR="$AGENTIC_WORKS_ERROR Marketplace, which may be unreachable from here — see $LOG"
  fi
  [ -z "$AGENTIC_WORKS_ERROR" ]
}

AGENTIC_WORKS_IN_PLACE=0  # 1 when the Agentic Works step leaves an Agentic Works installed (this release's, an older or a newer one)

ensure_agentic_works() {  # this release's Agentic Works: installed, upgraded over an older one, or a newer one left alone
  local current="" detail="installed $AGENTIC_WORKS_VERSION"
  skipped extension "Agentic Works" && return 0
  step_begin "Agentic Works"
  if [ -n "$CLASH" ]; then
    step_end failed "$CLASH"
    return 0
  fi
  if ! agentic_works_stamped; then
    step_end failed "this copy of the installer has no Agentic Works release in it; run a released installer: $LATEST_INSTALLER"
    return 0
  fi
  if find_code; then
    current=$(installed_version "$AGENTIC_WORKS_ID" "$(installed_extensions)")
  elif [ "$DRY_RUN" != 1 ]; then
    step_end skipped "VS Code isn't installed"
    return 0
  fi
  [ -z "$current" ] || AGENTIC_WORKS_IN_PLACE=1
  if [ -n "$current" ]; then
    case $(version_cmp "$current" "$AGENTIC_WORKS_VERSION") in
      eq) step_end already; return 0 ;;
      gt) step_end skipped "$current is newer than this installer's $AGENTIC_WORKS_VERSION; left as is"; return 0 ;;
    esac
    detail="upgraded from $current to $AGENTIC_WORKS_VERSION"
  fi
  case $OS in ubuntu|debian) apt_prereqs curl ;; esac  # not in a minimal system; a failure is reported just below
  if ! VSIX_DIR=$(mktemp -d "${TMPDIR:-/tmp}/agentic-works-install-vsix.XXXXXX"); then
    VSIX_DIR=""
    step_end failed "couldn't make a temp dir for the download"
    return 0
  fi
  install_agentic_works_vsix "$VSIX_DIR"
  rm -rf "$VSIX_DIR"
  VSIX_DIR=""
  if [ -n "$AGENTIC_WORKS_ERROR" ]; then
    step_end failed "$AGENTIC_WORKS_ERROR"
  elif [ "$DRY_RUN" = 1 ]; then
    [ -n "$current" ] || AGENTIC_WORKS_FRESH=1
    step_end done "dry run"
  else
    AGENTIC_WORKS_IN_PLACE=1
    step_end done "$detail"
    if [ -z "$current" ]; then AGENTIC_WORKS_FRESH=1; elif vscode_open; then RELOAD_VSCODE=1; fi
  fi
}

ensure_companions() {  # Claude Code and ChatGPT (Perch runs their claude and codex) and Perch's audio, by id
  local installed="" id missing="" failed="" agents=""
  skipped companions "Companions" && return 0
  step_begin "Companions"
  if [ -n "$CLASH" ]; then
    step_end skipped "skipped — Agentic Works was not installed"
    return 0
  fi
  if find_code; then
    installed=$(installed_extensions)
  elif [ "$DRY_RUN" != 1 ]; then
    step_end skipped "VS Code isn't installed"
    return 0
  fi
  for id in $COMPANIONS; do
    installed_version "$id" "$installed" > /dev/null || missing="$missing $id"
  done
  if [ -z "$missing" ]; then
    step_end already
    return 0
  fi
  for id in $missing; do
    code_cli --install-extension "$id" || failed="$failed $id"
  done
  case $failed in
    *anthropic.claude-code*|*openai.chatgpt*)
      agents="; Perch's tabs need Claude Code or ChatGPT to run an agent"
      [ "$AGENTIC_WORKS_IN_PLACE" = 0 ] || agents="; Agentic Works works, but${agents#;}" ;;
  esac
  # shellcheck disable=SC2086
  if [ "$DRY_RUN" = 1 ]; then
    step_end done "dry run"
  elif [ -n "$failed" ]; then
    step_end failed "$(commas $failed) didn't install (see $LOG)$agents"
  else
    step_end done "installed $(commas $missing)"
  fi
}

# ---- Linux: the launcher and the icon of Agentic Works' own VS Code (note 107) --------------------------------------

LAUNCHER=""  # ~/.local/bin/<slug>: runs VS Code on Agentic Works' own folders; the icon runs it, a company's command too
DESKTOP=""   # the desktop entry, in the app launcher

launcher_text() {  # the launcher script: the code found now, written in; if that one is gone, the first non-Cursor `code`
  printf '#!/usr/bin/env bash\n'
  printf "# %s: Agentic Works' own VS Code, on folders of its own (written by agentic-works-install; note 107)\n" "$NAME"
  printf 'code=%q\ndata=%q\next=%q\nshared=%q\n' "$CODE" "$OWN_DATA" "$OWN_EXT" "$OWN_SHARED"
  printf 'own=%q\n' "$OWN_HOME"  # its bin/code, and any other name's, runs a launcher: never taken for VS Code
  printf 'slug=%q\n' "$SLUG"
  cat <<'EOF_LAUNCHER'
if [ "${1:-}" = --print-folders ]; then
  printf 'data=%s\nextensions=%s\nshared=%s\n' "$data" "$ext" "$shared"
  exit 0
fi
if [ ! -x "$code" ]; then  # VS Code moved: another `code` on the PATH, never Cursor's, never this one (its bin/code)
  code=""
  while IFS= read -r c; do
    [ -n "$c" ] || continue
    r=$(readlink -f "$c" 2> /dev/null) || r=$c
    case "$c|$r" in "$own"/*/bin/code\|*|*\|"$own"/*/bin/code) continue ;; esac
    case "$(printf '%s %s' "$c" "$r" | tr '[:upper:]' '[:lower:]')" in */cursor*) continue ;; esac
    code=$c
    break
  done <<EOF_CODE
$(type -ap code 2> /dev/null)
EOF_CODE
  if [ -z "$code" ]; then
    printf "VS Code isn't installed; install it from https://code.visualstudio.com/download\n" >&2
    exit 1
  fi
fi
# The dock: VS Code started with this names its windows' class "$slug"_code, the desktop entry's StartupWMClass, so
# they show under its icon, apart from the user's own VS Code's. Agentic Works keeps it from what it starts.
export SNAP_INSTANCE_NAME=$slug
exec "$code" --user-data-dir "$data" --extensions-dir "$ext" --shared-data-dir "$shared" "$@"
EOF_LAUNCHER
}

desktop_text() {  # $1 = the Icon= value; StartupWMClass, the class the launcher's VS Code gives its windows (code: its applicationName)
  printf '[Desktop Entry]\nType=Application\nName=%s\nComment=%s\nExec="%s" %%F\nIcon=%s\nTerminal=false\n' \
    "$NAME" "Agentic Works' own VS Code" "$LAUNCHER" "$1"
  printf 'StartupWMClass=%s_code\nCategories=Development;IDE;\n' "$SLUG"
}

icon_source() {  # prints the picture the icon shows: --icon's (a PNG or an SVG), else the newest installed Agentic Works' own PNG; false when none
  local f best="" best_v="" v
  [ -z "$ICON_FILE" ] || { printf '%s\n' "$ICON_FILE"; return 0; }
  for f in "$OWN_EXT"/"$AGENTIC_WORKS_ID"-*/media/icon.png; do
    [ -f "$f" ] || continue
    v=${f#"$OWN_EXT/$AGENTIC_WORKS_ID-"}; v=${v%%/*}
    if [ -z "$best" ] || [ "$(version_cmp "$v" "$best_v")" = gt ]; then best=$f best_v=$v; fi
  done
  [ -n "$best" ] && printf '%s\n' "$best"
}

file_sum() {  # $1 = a file: its SHA-256, or nothing
  if have sha256sum; then sha256sum "$1" 2> /dev/null; else shasum -a 256 "$1" 2> /dev/null; fi | { read -r sum _; printf '%s' "${sum:-}"; }
}

ensure_launcher() {
  local label="Launcher" icon_src icon="vscode" kind other stale="" launcher_now desktop_now shim_now changed=0 restart=0
  [ "$OWN" = 1 ] || return 0
  skipped launcher "$label" && return 0
  LAUNCHER="$HOME/.local/bin/$SLUG"
  DESKTOP="${XDG_DATA_HOME:-$HOME/.local/share}/applications/$SLUG.desktop"
  step_begin "$label"
  if ! find_code && [ "$DRY_RUN" != 1 ]; then step_end failed "VS Code isn't installed"; return 0; fi
  if [ "$DRY_RUN" = 1 ]; then
    step_say "would write $LAUNCHER and $DESKTOP"
    ensure_claude_path
    step_end done "dry run"
    return 0
  fi
  if icon_src=$(icon_source); then
    kind=png other=svg
    png_file "$icon_src" || { kind=svg other=png; }
    icon="$OWN_ROOT/icon.$kind"
    if [ "$(file_sum "$icon_src")" != "$(file_sum "$icon")" ]; then
      cat "$icon_src" > "$icon" 2>> "$LOG" || { step_end failed "couldn't write $icon"; return 0; }
      changed=1
    fi
    # the picture it showed before, of the other kind: removed once the desktop entry no longer shows it
    [ ! -e "$OWN_ROOT/icon.$other" ] || stale="$OWN_ROOT/icon.$other"
  fi
  if [ -e "$LAUNCHER" ] && ! grep -q "written by agentic-works-install" "$LAUNCHER" 2> /dev/null; then
    step_end failed "$LAUNCHER is another command; run the installer with another --name"
    return 0
  fi
  launcher_now=$(launcher_text)
  desktop_now=$(desktop_text "$icon")
  if [ "$(cat "$LAUNCHER" 2> /dev/null)" != "$launcher_now" ]; then
    # the dock (note 107): a VS Code that a launcher from before it started shows under VS Code's icon until it is
    # started again; a reload doesn't do it
    if [ -f "$LAUNCHER" ] && ! grep -q SNAP_INSTANCE_NAME "$LAUNCHER" 2> /dev/null && own_running; then restart=1; fi
    { mkdir -p "${LAUNCHER%/*}" && printf '%s\n' "$launcher_now" > "$LAUNCHER" && chmod 755 "$LAUNCHER"; } 2>> "$LOG" ||
      { step_end failed "couldn't write $LAUNCHER"; return 0; }
    DOCK_RESTART=$restart  # once the launcher that gives it is there
    changed=1
  fi
  # <root>/bin/code runs the launcher; the settings step puts it first on the PATH of its own terminals (note 107)
  shim_now=$(printf '#!/usr/bin/env bash\nexec %q "$@"' "$LAUNCHER")
  if [ "$(cat "$OWN_ROOT/bin/code" 2> /dev/null)" != "$shim_now" ]; then
    { mkdir -p "$OWN_ROOT/bin" && printf '%s\n' "$shim_now" > "$OWN_ROOT/bin/code" && chmod 755 "$OWN_ROOT/bin/code"; } \
      2>> "$LOG" || { step_end failed "couldn't write $OWN_ROOT/bin/code"; return 0; }
    changed=1
  fi
  if [ "$(cat "$DESKTOP" 2> /dev/null)" != "$desktop_now" ]; then
    { mkdir -p "${DESKTOP%/*}" && printf '%s\n' "$desktop_now" > "$DESKTOP"; } 2>> "$LOG" ||
      { step_end failed "couldn't write $DESKTOP"; return 0; }
    changed=1
  fi
  if [ -n "$stale" ]; then
    rm -f "$stale" 2>> "$LOG" || { step_end failed "couldn't remove $stale"; return 0; }
    changed=1
  fi
  if ! ensure_claude_path; then
    step_end failed "$SLUG is in ~/.local/bin, but $(shell_profile) couldn't be written, so a new terminal won't find it"
    return 0
  fi
  if [ "$changed" = 1 ]; then step_end done "$SLUG and its icon"; else step_end already; fi
}

# ---- Claude Code's command-line tool, for a terminal ---------------------------------------------------------

profile_block_add() {  # $1 = profile, $2 = a line: into Agentic Works' PATH block (made when there is none); false on failure
  # The block is the one whose marker is a whole line "# added by agentic-works-install": the Homebrew block's marker
  # ("...: Homebrew") is another block, and the line never goes into it.
  local profile=$1 line=$2 text="" row start=0 end=0 i=0 n=0
  if [ -f "$profile" ]; then
    while IFS= read -r row || [ -n "$row" ]; do
      i=$((i + 1))
      if [ "$start" = 0 ]; then
        [ "$row" = "$PATH_MARK" ] && start=$i
      elif [ "$end" = 0 ] && [ "$row" = "$PATH_END" ]; then
        end=$i
      fi
    done < "$profile"
  fi
  if [ "$start" = 0 ] || [ "$end" = 0 ]; then
    printf '\n%s\n%s\n%s\n' "$PATH_MARK" "$line" "$PATH_END" >> "$profile"
    return
  fi
  while IFS= read -r row || [ -n "$row" ]; do
    n=$((n + 1))
    [ "$n" = "$end" ] && text="$text$line"$'\n'
    text="$text$row"$'\n'
  done < "$profile"
  printf '%s' "$text" > "$profile"  # in place: the file's mode and any symlink stay
}

claude_local_bin_planned() {  # true when ~/.local/bin isn't on the PATH a new terminal gets
  case ":$ORIG_PATH:" in *":$HOME/.local/bin:"*) return 1 ;; esac
  return 0
}

ensure_claude_path() {  # ~/.local/bin on the PATH for this run and, in Agentic Works' block, for new terminals; false on failure
  local dir="$HOME/.local/bin" profile line
  case ":$PATH:" in *":$dir:"*) ;; *) PATH="$dir:$PATH" ;; esac
  claude_local_bin_planned || return 0
  profile=$(shell_profile)
  line="case \":\$PATH:\" in *\":$dir:\"*) ;; *) export PATH=\"$dir:\$PATH\" ;; esac"
  if [ -f "$profile" ] && grep -qF "$line" "$profile"; then return 0; fi
  if [ "$DRY_RUN" = 1 ]; then
    step_say "\$ add to $profile, inside Agentic Works' block:"
    step_say "$line"
    return 0
  fi
  profile_block_add "$profile" "$line" 2>> "$LOG"
}

ensure_claude() {  # Claude Code's CLI, from Anthropic's installer (user-level: no sudo): `claude` in a terminal
  local label="Claude Code CLI" tmp rc
  [ -n "$CLASH" ] && return 0  # the run stopped at the standalone five
  skipped claude "$label" && return 0
  step_begin "$label"
  if [ -e "$HOME/.local/bin/claude" ]; then
    if ensure_claude_path; then
      step_end already
    else
      step_end failed "claude is in ~/.local/bin, but $(shell_profile) couldn't be written"
    fi
    return 0
  fi
  if have claude; then
    step_end already
    return 0
  fi
  case $OS in ubuntu|debian) apt_prereqs curl ;; esac  # not in a minimal system
  tmp=$(mktemp "${TMPDIR:-/tmp}/agentic-works-install-claude.XXXXXX") || { step_end failed "couldn't make a temp file; see $LOG"; return 0; }
  # Downloaded first, then run, as Homebrew's is: a failed download stops here rather than running an empty script.
  run curl -fsSL -o "$tmp" "$CLAUDE_INSTALLER" && run bash "$tmp"
  rc=$?
  rm -f "$tmp"
  if [ "$DRY_RUN" = 1 ]; then
    ensure_claude_path
    step_end done "dry run"
  elif [ "$rc" != 0 ] || [ ! -e "$HOME/.local/bin/claude" ]; then
    step_end failed "couldn't be installed; see $LOG"
  elif ensure_claude_path; then
    step_end done "installed"
  else
    step_end failed "installed in ~/.local/bin, but $(shell_profile) couldn't be written, so a new terminal won't find it"
  fi
}

# ---- git, which Claude Code, Codex and the PRs part expect to run --------------------------------------------

git_works() {  # true when `git --version` runs; on a Mac, Apple's /usr/bin/git shim without the CLT is never run
  local git=${AGENTIC_WORKS_INSTALL_GIT:-}
  [ -n "$git" ] || git=$(command -v git 2> /dev/null) || return 1
  if [ "$OS" = macos ] && [ "$git" = /usr/bin/git ] && ! xcode-select -p > /dev/null 2>&1; then
    return 1  # the shim would open Apple's install dialog
  fi
  printf '$ %s --version\n' "$git" >> "$LOG"
  "$git" --version < /dev/null >> "$LOG" 2>&1
}

wait_for_clt() {  # up to AGENTIC_WORKS_INSTALL_CLT_WAIT seconds for Apple's Command Line Tools; polled every 5 s (1 s if short)
  local wait=${AGENTIC_WORKS_INSTALL_CLT_WAIT:-600} step=5 elapsed=0
  case $wait in ''|*[!0-9]*) wait=600 ;; esac
  [ "$wait" -lt 10 ] && step=1
  while ! xcode-select -p > /dev/null 2>&1; do
    [ "$elapsed" -ge "$wait" ] && return 1
    sleep "$step"
    elapsed=$((elapsed + step))
  done
}

apple_installs_clt() {  # $1 = what needs them: Apple's own installer window for its Command Line Tools, waited for.
  # 0: they are there (a dry run: the install was printed); 1: the install couldn't be started; 2: not finished in time
  step_say "$1 needs Apple's Command Line Tools; Apple's installer window opens next"
  run xcode-select --install || return 1
  [ "$DRY_RUN" != 1 ] || return 0
  step_wait "waiting for Apple's install to finish"
  wait_for_clt || return 2
}

ensure_git() {
  local rc=0
  [ -n "$CLASH" ] && return 0  # the run stopped at the standalone five
  skipped git "git" && return 0
  step_begin "git"
  if git_works; then
    step_end already
    return 0
  fi
  case $OS in
    macos)
      if find_brew || [ "$HOMEBREW_STATE" = planned ]; then
        HOMEBREW_USED=1
        run "$(brew_bin)" install git || rc=1
      else
        apple_installs_clt git
        case $? in
          0) ;;
          2) step_end failed "finish the Command Line Tools install Apple opened, then run git --version"
             return 0 ;;
          *) rc=1 ;;
        esac
      fi ;;
    ubuntu|debian)  # a fresh machine's package lists may be stale or missing: updated first, as the other apt installs are
      # shellcheck disable=SC2086
      { run $SUDO apt-get update && run $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y git; } || rc=1 ;;
    rhel|fedora)
      # shellcheck disable=SC2086
      run $SUDO dnf install -y git || rc=1 ;;
  esac
  if [ "$DRY_RUN" = 1 ]; then
    step_end done "dry run"
  elif [ "$rc" != 0 ]; then
    step_end failed "couldn't be installed; see $LOG"
  else
    step_end done "installed"
  fi
}

# ---- GitHub, for kestrel's PRs panel -------------------------------------------------------------------------

GH_REPO_ADDED=0  # 1 once install_gh has added GitHub's package repository

install_gh() {  # GitHub's CLI: Homebrew; GitHub's apt or rpm repository; Fedora's own repository
  case $OS in
    macos)
      ensure_homebrew || return 1
      HOMEBREW_USED=1
      run "$(brew_bin)" install gh ;;
    ubuntu|debian)
      # shellcheck disable=SC2086
      if ! apt_has_source "cli.github.com/packages"; then
        apt_prereqs curl &&
          add_apt_repo "$GH_KEY" /usr/share/keyrings/githubcli-archive-keyring.gpg \
            /etc/apt/sources.list.d/github-cli.list \
            "deb [arch=$(deb_arch) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" \
            binary || return 1
        GH_REPO_ADDED=1
      fi
      # shellcheck disable=SC2086
      run $SUDO apt-get update && run $SUDO env DEBIAN_FRONTEND=noninteractive apt-get install -y gh ;;
    rhel)
      # Not `--repo gh-cli`, as GitHub's page has it: that hides the system repositories, and gh needs their git.
      # shellcheck disable=SC2086
      run $SUDO dnf install -y 'dnf-command(config-manager)' &&
        run $SUDO dnf config-manager --add-repo "$GH_RPM_REPO" || return 1
      GH_REPO_ADDED=1
      # shellcheck disable=SC2086
      run $SUDO dnf install -y gh ;;
    fedora)
      # shellcheck disable=SC2086
      run $SUDO dnf install -y gh ;;
  esac
}

github_user() {
  gh api user --jq .login < /dev/null 2>> "$LOG"
}

gh_signed_in() {
  printf '$ gh auth status\n' >> "$LOG"
  gh auth status < /dev/null >> "$LOG" 2>&1
}

ensure_github() {  # gh, for kestrel's PRs panel; the sign-in is Agentic Works' walkthrough's, never the terminal's
  local installed="" user
  [ -n "$CLASH" ] && return 0  # the run stopped at the standalone five
  skipped github "GitHub" && return 0
  step_begin "GitHub"
  if ! have gh; then
    if ! install_gh; then
      if [ "$OS" = macos ] && [ "$HOMEBREW_STATE" = failed ]; then
        step_end failed "gh comes through Homebrew, which $(homebrew_failure); see $LOG"
      else
        step_end failed "gh couldn't be installed; see $LOG"
      fi
      return 0
    fi
    if [ "$DRY_RUN" != 1 ] && ! have gh; then
      step_end failed "the install didn't give a 'gh' command; see $LOG"
      return 0
    fi
    installed="installed gh"
    [ "$GH_REPO_ADDED" = 0 ] || installed="added GitHub's package repository, $installed"
  fi
  if [ "$DRY_RUN" = 1 ]; then
    if [ -n "$installed" ]; then step_end done "$installed; dry run"; else step_end already; fi
    return 0
  fi
  if gh_signed_in; then
    user=$(github_user)
    if [ -n "$installed" ]; then
      step_end done "$installed; signed in${user:+ as $user}"
    else
      step_end already
      [ -z "$user" ] || step_say "signed in as $user"
    fi
  else
    if [ -n "$installed" ]; then step_end done "$installed"; else step_end already; fi
    step_say "sign in from Agentic Works' walkthrough in VS Code (Sign in to GitHub)"
  fi
}

ensure_homebrew_path() {  # macOS: Homebrew's shellenv in the login profile, when this run used Homebrew or a tool comes from it
  local label="Homebrew on the PATH" profile short brew dir tool found=0 lines
  [ "$OS" = macos ] || return 0
  [ -n "$CLASH" ] && return 0  # the run stopped at the standalone five
  skipped homebrew "$label" && return 0
  brew=$(brew_bin)
  dir=$(dirname "$brew")
  if [ "$HOMEBREW_USED" = 1 ]; then
    found=1
  elif find_brew; then
    for tool in code gh git; do
      [ "$(dirname "$(command -v "$tool" 2> /dev/null || echo /nonexistent/x)")" = "$dir" ] && found=1
    done
  fi
  [ "$found" = 1 ] || return 0  # Homebrew wasn't used: no line at all
  step_begin "$label"
  profile=$(shell_profile)
  short=${profile#"$HOME"/}
  if [ -f "$profile" ] && grep -q 'brew shellenv' "$profile"; then
    step_end already
    return 0
  fi
  case ":$ORIG_PATH:" in *":$dir:"*) step_end already; return 0 ;; esac
  lines="[ -x $brew ] && eval \"\$($brew shellenv)\""
  if [ "$DRY_RUN" = 1 ]; then
    step_say "\$ append to $profile:"
    step_say "$lines"
    step_end done "dry run"
    return 0
  fi
  if printf '\n%s\n%s\n%s\n' "$PATH_MARK: Homebrew" "$lines" "$PATH_END" >> "$profile"; then
    step_end done "$short"
  else
    step_end failed "couldn't write $profile"
  fi
}

# ---- the look: settings and icons, through agentic-works-install-helper; then VS Code opens ---------------------------

HELPER_OUT=""
PYTHON=""  # the python3 the helper runs with; python_ok finds it
PYTHON_WHY=""  # why there is none, when python_ok is false
PYTHON_PLACEHOLDER=0  # 1 when python_ok found only a Mac's own python3 with Apple's Command Line Tools missing

write_inlined_helper() {  # a released script carries the helper as a here-document (make release fills this in)
  INLINED_HELPER=$(mktemp "${TMPDIR:-/tmp}/agentic-works-install-helper.XXXXXX") || return 1
  cat > "$INLINED_HELPER" << 'AGENTIC_WORKS_INSTALL_HELPER_END' || { rm -f "$INLINED_HELPER"; INLINED_HELPER=""; return 1; }
#!/usr/bin/env python3
"""agentic-works-install-helper: the JSON and SQLite edits the bash installer `agentic-works-install.sh` delegates to.

Each subcommand exits 0 when done, 2 when it skipped (reason on stdout), 1 on error.

Runs on Python 3.6 (RHEL 8's python3), stdlib only: typing's List/Optional rather than list[...] or X | None, no
`from __future__ import annotations`, subprocess.run without capture_output, no Path.unlink(missing_ok=).
"""

import argparse
import hashlib
import json
import os
import re
import shutil
import socket
import sqlite3
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union

EXIT_DONE, EXIT_ERROR, EXIT_SKIPPED = 0, 1, 2

WANTED_SETTINGS = {
    "chat.disableAIFeatures": True,
    "workbench.startupEditor": "none",
    "workbench.secondarySideBar.defaultVisibility": "hidden",
    "workbench.activityBar.location": "top",
    # a file opened from the Explorer gets a tab of its own, and the group whose last file closes stays where it is,
    # so the Claude tab's group keeps its place on the right (note 102)
    "workbench.editor.enablePreview": False,
    "workbench.editor.closeEmptyGroups": False,
}
# --codebase-search: the installer's question answered yes (default); added only when absent, like the rest
CODEBASE_SEARCH = {"agents.codebaseIndex.enabled": True}
# --teams-app <clientId>:<tenant>: a company's own Microsoft app for the Teams part's sign-in, added only when absent
TEAMS_APP_KEYS = ("teams.signIn.clientId", "teams.signIn.tenant")
TERMINAL_ENV_KEY = "terminal.integrated.env.linux"  # AGENTIC_WORKS_TERMINAL_BIN: its `code` first on the PATH
GUID = r"[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}"
DOMAIN = r"(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}"
TEAMS_APP = re.compile(r"^(%s):(%s|%s)$" % (GUID, GUID, DOMAIN))
PINNED_KEY = "workbench.activity.pinnedViewlets2"
LAYOUT_RECORD_KEY = "agenticWorks.installer.layoutWritten"  # in state.vscdb: the layout was written once; never again
SHOWN_VIEWLETS = [
    "workbench.view.explorer",
    "workbench.view.search",
    "workbench.view.extensions",
    "workbench.view.extension.perch",
    "workbench.view.extension.chirp",
    "workbench.view.extension.jay",
]
HIDDEN_VIEWLETS = [
    "workbench.view.scm",
    "workbench.view.debug",
    "workbench.view.testing",
    "workbench.view.extension.claude-sidebar",
    "workbench.view.extension.claude-sessions-sidebar",
]

# Claude Code's and Codex's "open" buttons, which they put on every editor's title bar (Get started included; Sean,
# 2026-11-25). Hidden as a right-click in the title bar would: VS Code keeps that per profile in state.vscdb, as
# {menu id: [command ids]}; there is no setting for it. Their diff buttons (accept, reject) are left alone.
HIDDEN_COMMANDS_KEY = "menu.hiddenCommands"
HIDDEN_TITLE_COMMANDS = ["claude-vscode.editor.openLast", "claude-vscode.terminal.open", "chatgpt.openSidebar"]

# The panel's Debug Console tab (Sean, 2026-11-29), as Run and Debug's icon is hidden above. Hidden as a right-click on
# the tab would: VS Code keeps the panel's tabs in state.vscdb as it keeps the activity bar's icons (the same composite
# bar, under another key), unpinned ones hidden and those it doesn't list shown; there is no setting for it.
PANELS_KEY = "workbench.panel.pinnedPanels"
HIDDEN_PANELS = ["workbench.panel.repl"]


def hidden_commands(value: Optional[str]) -> Optional[str]:
    """menu.hiddenCommands with the vendor title buttons added to EditorTitle; None when the value isn't such JSON."""
    try:
        data = json.loads(value) if value else {}
    except ValueError:
        return None
    if not isinstance(data, dict) or not isinstance(data.get("EditorTitle", []), list):
        return None
    title = data.get("EditorTitle", [])
    data["EditorTitle"] = title + [c for c in HIDDEN_TITLE_COMMANDS if c not in title]
    return json.dumps(data)


def hidden_panels(value: Optional[str]) -> Optional[str]:
    """workbench.panel.pinnedPanels with Debug Console hidden, other entries kept; None when the value isn't such JSON."""
    try:
        data = json.loads(value) if value else []
    except ValueError:
        return None
    if not isinstance(data, list):
        return None
    kept = [e for e in data if not (isinstance(e, dict) and e.get("id") in HIDDEN_PANELS)]
    return json.dumps(kept + [{"id": pid, "pinned": False, "visible": False} for pid in HIDDEN_PANELS])


def user_dir() -> Path:
    """VS Code's User folder, found as VS Code finds it (the installer names another when it gives VS Code one)."""
    override = os.environ.get("AGENTIC_WORKS_VSCODE_USER_DIR")
    if override:
        return Path(override)
    if sys.platform == "darwin":
        return Path.home() / "Library" / "Application Support" / "Code" / "User"
    config = os.environ.get("XDG_CONFIG_HOME")
    return (Path(os.path.abspath(config)) if config else Path.home() / ".config") / "Code" / "User"


PROFILE = None  # type: Optional[str]  # --profile NAME: the VS Code profile the settings and layout go into


def _storage() -> Path:
    """VS Code's storage.json: its profiles (userDataProfiles) and its windows."""
    return user_dir() / "globalStorage" / "storage.json"


def _read_storage() -> dict:
    """storage.json as a dict ({} when absent); ValueError when it isn't a JSON object."""
    path = _storage()
    data = json.loads(path.read_text(encoding="utf-8") or "{}") if path.exists() else {}
    if not isinstance(data, dict) or not isinstance(data.get("userDataProfiles", []), list):
        raise ValueError(f"{path} isn't a JSON object of VS Code's")
    return data


def _location_in(data: dict, name: str) -> Optional[str]:
    for entry in data.get("userDataProfiles", []):
        if isinstance(entry, dict) and entry.get("name") == name and isinstance(entry.get("location"), str):
            return entry["location"]
    return None


def profile_location(name: str) -> Optional[str]:
    """The folder under User/profiles of the profile named name; None when there is none."""
    return _location_in(_read_storage(), name)


def target_dir() -> Path:
    """Where settings.json and globalStorage are: the --profile's folder, else the user's own. ValueError when that
    profile hasn't been made."""
    if PROFILE is None:
        return user_dir()
    location = profile_location(PROFILE)
    if location is None:
        raise ValueError(f"VS Code has no profile named {PROFILE!r}")
    return user_dir() / "profiles" / location


# Copied from the user's own profile into a new one, with their settings (see _new_settings), so it starts as theirs;
# extensions and state are not.
PROFILE_COPIES = ("keybindings.json", "tasks.json", "snippets")


def _blank(path: Path) -> bool:
    """A file with nothing in it: absent, empty, or {} or [] (what VS Code writes in a profile it makes)."""
    try:
        return not path.exists() or path.is_file() and path.read_text(encoding="utf-8").strip() in ("", "{}", "[]")
    except (OSError, UnicodeDecodeError):
        return False


def _new_settings(look: bool) -> Optional[bytes]:
    """What a new profile's settings.json starts as: the user's own, and with look the look's keys added where
    absent, so the window VS Code opens to make the profile starts with the look. The user's own as it is when it
    has comments or isn't UTF-8. None when there is nothing to write."""
    path = user_dir() / "settings.json"
    raw = path.read_bytes() if path.is_file() else b""
    if look:
        try:
            merged = merge_settings(raw.decode("utf-8"), WANTED_SETTINGS)
        except UnicodeDecodeError:
            merged = None
        if merged is not None:
            return merged.encode("utf-8")
    return None if _blank(path) else raw


def _copy_users_files(folder: Path, settings: Optional[bytes]) -> Tuple[bool, bool]:
    """A profile's blank files filled: settings.json with settings (see _new_settings), and keybindings, tasks and
    snippets with the user's own. Returns whether anything was written, and whether any of it was the user's."""
    wrote = theirs = False
    if settings is not None and _blank(folder / "settings.json"):
        _write_atomic(folder / "settings.json", settings)
        wrote, theirs = True, not _blank(user_dir() / "settings.json")
    for name in PROFILE_COPIES:
        source, dest = user_dir() / name, folder / name
        if source.is_dir() and not dest.exists():
            shutil.copytree(str(source), str(dest))
            wrote = theirs = True
        elif source.is_file() and not _blank(source) and _blank(dest):
            shutil.copyfile(str(source), str(dest))
            wrote = theirs = True
    return wrote, theirs


FRESH = 5.0  # seconds before the wait began: a folder changed no longer ago is one VS Code is making now


def _new_profile_folder(listed: set, since: float) -> Optional[Path]:
    """The folder VS Code is making a profile in, before storage.json lists it: the one folder under User/profiles
    that isn't listed and was made since `since`. None when there is none, or more than one."""
    try:
        new = [p for p in (user_dir() / "profiles").iterdir()
               if p.name not in listed and p.is_dir() and p.stat().st_ctime >= since]
    except OSError:
        return None
    return new[0] if len(new) == 1 else None


def _await_profile(name: str, seconds: float, settings: Optional[bytes]) -> Tuple[Optional[str], bool]:
    """Wait up to seconds for VS Code to list the profile name, as it does once a window is opened on it. Returns
    its folder (None: it never came) and whether settings went into it meanwhile.

    The window reads its profile's settings.json once, about 0.1 s after storage.json lists the profile, and watches
    the file only a second later: one written in between isn't applied until it is written again (VS Code 1.129,
    2026-11-28). So settings go into the folder as soon as VS Code makes it, about 0.1 s before the profile is listed.
    If the profile turns out to be another folder, or never comes, that file is taken back unless it changed."""
    since, deadline = time.time() - FRESH, time.monotonic() + seconds
    early = None  # type: Optional[Path]
    location = None  # type: Optional[str]
    while True:
        try:
            data = _read_storage()  # type: Optional[dict]
        except (OSError, ValueError, UnicodeDecodeError):
            data = None  # VS Code is writing it
        if data is not None:
            location = _location_in(data, name)
            if location is not None:
                break
            if early is None and settings is not None:
                listed = {e.get("location") for e in data.get("userDataProfiles", []) if isinstance(e, dict)}
                folder = _new_profile_folder(listed, since)
                if folder is not None and not (folder / "settings.json").exists():
                    try:
                        _write_atomic(folder / "settings.json", settings)
                        early = folder / "settings.json"
                    except OSError:
                        pass  # the fill, once the profile is listed, writes it
        if time.monotonic() >= deadline:
            break
        time.sleep(0.01)
    if early is not None and (location is None or early.parent.name != location):
        try:
            if early.read_bytes() == settings:
                early.unlink()
        except OSError:
            pass
        early = None
    return location, early is not None


def _fill_profile(args: argparse.Namespace) -> int:
    """--fill: the user's files into the profile args.name, which VS Code made, where its own are blank; with --look
    the look goes into its settings with them, and with --wait VS Code is given that long to make it."""
    settings = _new_settings(args.look)
    early = False
    if args.wait:
        location, early = _await_profile(args.name, args.wait, settings)
        if location is None:
            print("VS Code didn't make it")
            return EXIT_SKIPPED
    else:
        location = profile_location(args.name)
        if location is None:
            print(f"agentic-works-install-helper: VS Code has no profile named {args.name!r}", file=sys.stderr)
            return EXIT_ERROR
    wrote, theirs = _copy_users_files(user_dir() / "profiles" / location, settings)
    if theirs or early and not _blank(user_dir() / "settings.json"):
        print("filled")
    else:
        print("look set" if wrote or early else "already set")
    return EXIT_DONE


def cmd_vscode_profile(args: argparse.Namespace) -> int:
    """Make the VS Code profile args.name, with the user's settings, keybindings and snippets copied in; one already
    there is left as it is. Not while VS Code runs: it rewrites storage.json from memory and the new profile would
    be lost (it makes its own, empty, when a window is opened on the name)."""
    if args.fill:
        return _fill_profile(args)
    try:
        data = _read_storage()
    except (ValueError, UnicodeDecodeError) as exc:
        print(f"agentic-works-install-helper: {exc}", file=sys.stderr)
        return EXIT_ERROR
    location = profile_location(args.name)
    if location is not None:
        print("already set")
        return EXIT_DONE
    if vscode_running():
        print("VS Code is running: it makes the profile itself when a window is opened on it.")
        return EXIT_SKIPPED
    taken = {e.get("location") for e in data.get("userDataProfiles", []) if isinstance(e, dict)}
    base = "agentic-works-" + hashlib.sha256(args.name.encode("utf-8")).hexdigest()[:8]
    location, n = base, 1
    while location in taken or (user_dir() / "profiles" / location).exists():
        n += 1
        location = f"{base}-{n}"
    folder = user_dir() / "profiles" / location
    folder.mkdir(parents=True)
    copied = _copy_users_files(folder, _new_settings(False))[1]
    data["userDataProfiles"] = data.get("userDataProfiles", []) + [{"location": location, "name": args.name}]
    _write_atomic(_storage(), json.dumps(data, indent=4) + "\n")
    print("made, with your settings" if copied else "made")
    return EXIT_DONE


def extensions_dir() -> Path:
    override = os.environ.get("AGENTIC_WORKS_VSCODE_EXTENSIONS_DIR")
    return Path(override) if override else Path.home() / ".vscode" / "extensions"


def merge_settings(text: str, wanted: dict, upgrade: Optional[dict] = None) -> Optional[str]:
    """Add the wanted keys that are absent, and put the wanted value in place of one an earlier installer wrote
    (upgrade: key -> that value, exactly; any other value is the user's); None when the text is not plain JSON (JSONC).

    When nothing changes the text is returned unchanged, so callers can detect a no-op by equality.
    """
    if text.strip():
        try:
            data = json.loads(text)
        except ValueError:
            return None
        if not isinstance(data, dict):
            return None
    else:
        data = {}
    old = upgrade or {}
    missing = {k: v for k, v in wanted.items() if k not in data or (k in old and data[k] == old[k])}
    if not missing and text.strip():
        return text
    data.update(missing)
    return json.dumps(data, indent=4, ensure_ascii=False) + "\n"


def _write_atomic(path: Path, text: Union[str, bytes]) -> None:
    """Replace path with text via a private temp file; keeps the mode.

    A symlink is followed: its target is replaced and the link stays (a dotfiles repo's settings.json)."""
    path = Path(os.path.realpath(path))
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_name(path.name + ".agentic-works-tmp")
    try:
        tmp.unlink()
    except FileNotFoundError:
        pass
    fd = os.open(str(tmp), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(fd, "wb") as fh:
        fh.write(text if isinstance(text, bytes) else text.encode("utf-8"))
    if path.exists():
        os.chmod(str(tmp), path.stat().st_mode & 0o7777)
    else:
        os.chmod(str(tmp), 0o644)
    os.replace(str(tmp), str(path))


def teams_app(value: str) -> Dict[str, str]:
    """`<clientId>:<tenant>` as the two Teams settings; the tenant is a GUID or a domain. ValueError when not."""
    match = TEAMS_APP.match(value.strip())
    if not match:
        raise ValueError("--teams-app takes <clientId>:<tenant>: a GUID, then a tenant GUID or domain")
    return dict(zip(TEAMS_APP_KEYS, (match.group(1).lower(), match.group(2).lower())))


def _has_any(text: str, keys: tuple) -> bool:
    """Whether plain-JSON settings text has any of the keys (JSONC: no, its lines are printed for the user to add)."""
    try:
        data = json.loads(text) if text.strip() else {}
    except ValueError:
        return False
    return isinstance(data, dict) and any(k in data for k in keys)


REWRITE_MAX = 60.0  # seconds: the longest --rewrite waits


def _write_again(path: Path) -> None:
    """Replace a file with itself, byte for byte: VS Code reads a settings.json again when it is written."""
    if path.exists():
        _write_atomic(path, path.read_bytes())


def cmd_vscode_settings(args: argparse.Namespace) -> int:
    """Merge the wanted keys into VS Code user settings.json without overwriting a key or rewriting JSONC.

    --rewrite SECONDS, for the settings of a profile whose window VS Code opened during this run: that window misses a
    settings.json written before it watches the file, about a second after it opens (VS Code 1.129, 2026-11-28). So
    wait that long (the rest of the time the installer gives the window) and write the file though nothing in it
    changes; what is said stays what a run without it says."""
    path = target_dir() / "settings.json"
    wanted = dict(WANTED_SETTINGS)
    if args.codebase_search:
        wanted.update(CODEBASE_SEARCH)
    terminal_bin = os.environ.get("AGENTIC_WORKS_TERMINAL_BIN")
    upgrade = {}  # type: Dict[str, dict]
    if terminal_bin:
        # Agentic Works' own VS Code (note 107): a local VS Code gives `code` in its terminal no way to find the
        # instance it runs in, so `code` would open in the user's; the installer's <root>/bin/code is the launcher.
        # And the CHROME_DESKTOP that VS Code made of the launcher's SNAP_INSTANCE_NAME (the dock) is taken out: an
        # Electron program started from one of its terminals would put its windows under this one's icon (VS Code
        # takes SNAP_* out of its terminals itself). An earlier installer wrote PATH alone; that value is brought up
        # to date.
        path_first = terminal_bin + ":${env:PATH}"
        wanted[TERMINAL_ENV_KEY] = {"PATH": path_first, "CHROME_DESKTOP": None}
        upgrade[TERMINAL_ENV_KEY] = {"PATH": path_first}
    pair = {}  # type: Dict[str, str]
    if args.teams_app:
        try:
            pair = teams_app(args.teams_app)
        except ValueError as exc:
            print(f"agentic-works-install-helper: {exc}", file=sys.stderr)
            return EXIT_ERROR
    again = args.rewrite is not None
    if again and args.rewrite > 0:
        time.sleep(min(args.rewrite, REWRITE_MAX))
    try:
        text = path.read_text(encoding="utf-8") if path.exists() else ""
        # the two go together: either already set keeps both as they are, so an app never meets another's tenant
        if pair and not _has_any(text, TEAMS_APP_KEYS):
            wanted.update(pair)
        merged = merge_settings(text, wanted, upgrade)
    except UnicodeDecodeError:
        merged = None
    if merged is None:
        if again:
            _write_again(path)
        print(f"{path} has comments or is not plain UTF-8 JSON; not rewriting it. Add these lines yourself:")
        for key, value in wanted.items():
            print(f"    {json.dumps(key)}: {json.dumps(value)},")
        return EXIT_SKIPPED
    if merged == text:
        if again:
            _write_again(path)
        print("already set")
        return EXIT_DONE
    _write_atomic(path, merged)
    if args.codebase_search and "agents.codebaseIndex.enabled" not in json.loads(text.strip() or "{}"):
        print("codebase search added")  # the installer's cue for its hint; a value already there was kept
    return EXIT_DONE


def layout_entry(existing: List[Dict], hidden_extra: List[str]) -> List[Dict]:
    entry = [{"id": vid, "pinned": True, "visible": True, "order": i} for i, vid in enumerate(SHOWN_VIEWLETS)]
    hidden = HIDDEN_VIEWLETS + [vid for vid in hidden_extra if vid not in HIDDEN_VIEWLETS]
    entry += [{"id": vid, "pinned": False, "visible": False} for vid in hidden]
    managed = set(SHOWN_VIEWLETS) | set(hidden)
    entry += [e for e in existing if e.get("id") not in managed]
    return entry


def codex_container_ids() -> List[str]:
    """Activity-bar container ids of the installed openai.chatgpt extension, as workbench view ids."""
    ids = []  # type: List[str]
    root = extensions_dir()
    if not root.is_dir():
        return ids
    for pkg in sorted(root.glob("openai.chatgpt-*/package.json")):
        try:
            data = json.loads(pkg.read_text(encoding="utf-8"))
            containers = data["contributes"]["viewsContainers"]["activitybar"]
        except (OSError, ValueError, KeyError, TypeError):
            continue
        for container in containers:
            cid = container.get("id") if isinstance(container, dict) else None
            if cid and f"workbench.view.extension.{cid}" not in ids:
                ids.append(f"workbench.view.extension.{cid}")
    return ids


def vscode_running() -> bool:
    """True while a VS Code runs on this user data directory: its code.lock names the main process, alive.

    Only that VS Code matters (it rewrites state.vscdb and storage.json on exit); another one, on another data
    directory, does not. A process scan skipped the layout whenever any VS Code was open (Sean's runs with a test
    home, 2026-11-24). No lock file: none runs here."""
    pid = _lock_pid()
    if pid is None:
        return False
    try:
        os.kill(pid, 0)
    except ProcessLookupError:
        return False
    except PermissionError:
        return True  # alive, another user's
    return True


def _lock_pid() -> Optional[int]:
    """The process code.lock names as this user data directory's VS Code; None with no lock, or with something in it
    that isn't a process number as VS Code writes one, in plain digits (Python would read zeros or a sign in front as
    a number too; 0 or less would name a group of processes; one too large makes os.kill raise)."""
    try:
        text = (user_dir().parent / "code.lock").read_text(encoding="utf-8").strip()
    except (OSError, ValueError):
        return None
    if not re.fullmatch(r"[1-9][0-9]{0,9}", text):
        return None
    pid = int(text)
    return pid if pid < 2 ** 31 else None


def _main_socket(version: str) -> Optional[Path]:
    """Where the `code` of that version, run in this environment, looks for a VS Code already running on this user data
    directory: the socket VS Code's main process listens on (createStaticIPCHandle in VS Code's source; seen beside
    1.129.1, 2026-11-28). It is named after the directory and the first four characters of the version, so the `code`
    of an update put on disk since doesn't find the VS Code still running. None when it can't be told: no version, or
    an environment that names VS Code other data (a portable one, VSCODE_APPDATA, a build from source)."""
    if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", version):
        return None
    if any(os.environ.get(name) for name in ("VSCODE_PORTABLE", "VSCODE_APPDATA", "VSCODE_DEV")):
        return None
    data = os.path.abspath(str(user_dir().parent))
    name = version[:4] + "-main.sock"
    runtime = os.environ.get("XDG_RUNTIME_DIR")
    if sys.platform != "darwin" and runtime:
        scope = hashlib.sha256(data.encode("utf-8")).hexdigest()[:8]
        return Path(runtime) / ("vscode-" + scope + "-" + name)
    return Path(data) / name


def vscode_answers(version: str) -> bool:
    """True when a `code` of that version, run now in this environment, would be handed to a VS Code already running
    on this user data directory: something answers on the socket it looks for. That is VS Code's own test (it starts
    a VS Code when nothing does, though the socket's file be there), and stricter than vscode_running: code.lock
    outlives a VS Code that crashed, and says nothing of which `code` reaches the one alive."""
    path = _main_socket(version)
    if path is None:
        return False
    try:
        client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    except (AttributeError, OSError):
        return False
    try:
        client.settimeout(2)
        client.connect(str(path))  # connected and closed: VS Code takes no notice (tried beside 1.129.1)
    except (OSError, ValueError):
        return False
    finally:
        client.close()
    return True


def cmd_vscode_running(args: argparse.Namespace) -> int:
    """Done (0) when the `code` of --code-version, run now, opens a window in a VS Code already running, so options
    given with it hold for that window alone; skipped (2) when it would start a VS Code, or may."""
    if vscode_answers(args.code_version):
        print("running")
        return EXIT_DONE
    print("VS Code isn't surely running")
    return EXIT_SKIPPED


def _has_key(db: Path, key: str) -> bool:
    if not db.exists():
        return False
    try:
        con = sqlite3.connect(f"{db.as_uri()}?mode=ro", uri=True)
        try:
            return con.execute("SELECT 1 FROM ItemTable WHERE key = ?", (key,)).fetchone() is not None
        finally:
            con.close()
    except sqlite3.Error:
        return False


def layout_recorded(db: Path) -> bool:
    """True once this installer has written the layout into this state.vscdb (it is written only once)."""
    return _has_key(db, LAYOUT_RECORD_KEY)


def layout_needed(db: Path) -> bool:
    """True when VS Code never started here: state.vscdb is absent or holds no activity-bar layout."""
    return not _has_key(db, PINNED_KEY)


# VS Code's first window, maximized: a fresh install opens one about 60% of the screen, too narrow for the Get
# started walkthrough's detail column beside the side bar (Sean's first-time run, 2026-11-24). VS Code keeps the last
# window's state in storage.json; mode 0 is maximized, and the size is what un-maximizing returns to (VS Code ignores
# a state without one). Written with the layout, only on a VS Code that never started, and only when absent.
FIRST_WINDOW = {"lastActiveWindow": {"uiState": {"mode": 0, "x": 80, "y": 60, "width": 1440, "height": 900}}, "openedWindows": []}


def maximize_first_window(storage: Path) -> None:
    """Add windowsState to storage.json when it has none; a file that isn't a JSON object is left alone."""
    data = {}
    if storage.exists():
        try:
            data = json.loads(storage.read_text(encoding="utf-8") or "{}")
        except (ValueError, UnicodeDecodeError):
            return
        if not isinstance(data, dict) or "windowsState" in data:
            return
    data["windowsState"] = FIRST_WINDOW
    _write_atomic(storage, json.dumps(data, indent=4) + "\n")


def cmd_vscode_layout(_args: argparse.Namespace) -> int:
    """Write the activity-bar layout, the hidden title-bar buttons and the panel's hidden tab once, recorded in the
    same transaction; later runs, and a VS Code that already has a layout, are left alone."""
    db = target_dir() / "globalStorage" / "state.vscdb"
    if layout_recorded(db):
        print("already set")
        return EXIT_DONE
    if not layout_needed(db):
        print("VS Code already has an icon layout; leaving it as it is.")
        return EXIT_SKIPPED
    if vscode_running():
        print("VS Code is running: quit VS Code and rerun.")
        return EXIT_SKIPPED
    db.parent.mkdir(parents=True, exist_ok=True)
    con = sqlite3.connect(str(db))  # a Path only from 3.7
    try:
        con.execute("CREATE TABLE IF NOT EXISTS ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB)")
        entry = layout_entry([], codex_container_ids())
        written = datetime.now(timezone.utc).isoformat(timespec="seconds")
        con.execute("INSERT INTO ItemTable (key, value) VALUES (?, ?)", (PINNED_KEY, json.dumps(entry)))
        row = con.execute("SELECT value FROM ItemTable WHERE key = ?", (HIDDEN_COMMANDS_KEY,)).fetchone()
        hidden = hidden_commands(row[0] if row else None)
        if hidden is not None:
            con.execute("INSERT INTO ItemTable (key, value) VALUES (?, ?)", (HIDDEN_COMMANDS_KEY, hidden))
        row = con.execute("SELECT value FROM ItemTable WHERE key = ?", (PANELS_KEY,)).fetchone()
        panels = hidden_panels(row[0] if row else None)
        if panels is not None:
            con.execute("INSERT INTO ItemTable (key, value) VALUES (?, ?)", (PANELS_KEY, panels))
        con.execute("INSERT INTO ItemTable (key, value) VALUES (?, ?)", (LAYOUT_RECORD_KEY, written))
        con.commit()
    finally:
        con.close()
    maximize_first_window(_storage())  # the app's windows: storage.json is the user's own, whatever the profile
    return EXIT_DONE


NO_ONBOARDING = {"workbench.welcomePage.experimentalOnboarding": False}


def cmd_vscode_no_onboarding(_args: argparse.Namespace) -> int:
    """VS Code's first-launch welcome (its Copilot sign-in) off, in the user's own settings.json, whatever --profile.

    The setting is application-wide, so VS Code reads it only from there. With VS Code open, the window that makes a
    profile starts before the profile has its settings (Copilot off among them), and on VS Code's very first launch it
    showed the welcome (2026-11-27). A value there is kept; JSONC is left alone."""
    path = user_dir() / "settings.json"
    try:
        text = path.read_text(encoding="utf-8") if path.exists() else ""
        merged = merge_settings(text, NO_ONBOARDING)
    except UnicodeDecodeError:
        merged = None
    if merged is None:
        print(f"{path} has comments or is not plain UTF-8 JSON; not rewriting it")
        return EXIT_SKIPPED
    if merged == text:
        print("already set")
        return EXIT_DONE
    _write_atomic(path, merged)
    print("added")
    return EXIT_DONE


# The company's own mark on the AI activity bar (note 101): VS Code takes that icon from Agentic Works' manifest, as this
# file in its folder (the bird as shipped), and reads it as a window starts. Agentic Works copies its company file's
# icons.ai over it as it starts, shown from the start after; the installer does it before the first.
AGENTIC_WORKS_FOLDERS = "agenticworks.agentic-works-*"  # an installed Agentic Works, as VS Code names its folder
AI_ICON = Path("parts", "agents", "media", "ai.svg")
BAD_AI_ICON = "the company file's icons.ai isn't an .svg file beside it, or { light, dark } of them"


def company_file() -> Path:
    """The company file, where Agentic Works looks for it (src/company.js)."""
    override = os.environ.get("AGENTIC_WORKS_COMPANY_FILE")
    return Path(override) if override else Path.home() / ".config" / "agentic-works" / "company.json"


def company_ai_icon() -> Tuple[Optional[Path], bool]:
    """The light file of the company file's icons.ai, as Agentic Works reads it (src/company.js): an .svg named from the
    company file's folder (or a ~/ path), one file or { light, dark }, both there. (None, False) when there's no company
    file Agentic Works reads (a JSON object with a name) or no icons.ai in it; (None, True) when icons.ai is bad."""
    path = company_file()
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except (OSError, ValueError):  # absent or unreadable; not UTF-8 or not JSON (both ValueErrors)
        return None, False
    if not isinstance(data, dict) or not isinstance(data.get("name"), str) or not data["name"]:
        return None, False
    icons = data.get("icons")
    if not isinstance(icons, dict) or "ai" not in icons:
        return None, False
    folder = Path(os.path.abspath(str(path))).parent  # as path.resolve has it: a symlink is not followed

    def svg(name: object) -> Optional[Path]:
        if not isinstance(name, str) or not name.lower().endswith(".svg"):
            return None
        found = Path.home() / name[2:] if name.startswith("~/") else folder / name  # an absolute name is itself
        return found if found.is_file() else None

    entry = icons["ai"]
    light = svg(entry.get("light") if isinstance(entry, dict) else entry)
    dark = svg(entry.get("dark") if isinstance(entry, dict) else entry)
    return (light, False) if light and dark else (None, True)


def cmd_ai_icon(_args: argparse.Namespace) -> int:
    """The company's mark as each installed Agentic Works' AI activity bar icon, before VS Code starts. Prints nothing
    when the company file names none."""
    mark, bad = company_ai_icon()
    if bad:
        print(BAD_AI_ICON)
        return EXIT_SKIPPED
    if mark is None:
        return EXIT_DONE
    folders = sorted(extensions_dir().glob(AGENTIC_WORKS_FOLDERS))
    if not folders:
        print(f"Agentic Works isn't installed in {extensions_dir()}")
        return EXIT_SKIPPED
    icons = [folder / AI_ICON for folder in folders if (folder / AI_ICON).is_file()]
    if not icons:  # one older than the company's icon: its manifest shows the bird's own file, which stays the bird
        print("the Agentic Works installed here is too old to show it")
        return EXIT_SKIPPED
    want = mark.read_bytes()
    changed = [icon for icon in icons if icon.read_bytes() != want]
    for icon in changed:
        _write_atomic(icon, want)
    print(f"the company's mark, {mark.name}" if changed else "already set")
    return EXIT_DONE


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="agentic-works-install-helper", description=__doc__)
    parser.add_argument("--profile", metavar="NAME", help="the VS Code profile the settings and layout go into")
    sub = parser.add_subparsers(dest="command")
    sub.required = True  # add_subparsers(required=) is 3.7+
    settings = sub.add_parser("vscode-settings", help="merge Agentic Works' keys into VS Code user settings.json")
    settings.add_argument("--codebase-search", action="store_true", help="also turn on the agents' codebase search")
    settings.add_argument("--teams-app", metavar="CLIENT_ID:TENANT",
                          help="also set the Teams sign-in's company app (teams.signIn.clientId and .tenant)")
    settings.add_argument("--rewrite", type=float, metavar="SECONDS",
                          help="wait SECONDS (60 at most), then write the file though nothing in it changes: a window "
                               "VS Code opened during this run reads it again")
    settings.set_defaults(func=cmd_vscode_settings)
    sub.add_parser("vscode-layout", help="write the activity-bar layout into state.vscdb").set_defaults(
        func=cmd_vscode_layout
    )
    sub.add_parser("vscode-no-onboarding", help="turn VS Code's first-launch welcome off in the user's own settings.json"
                   ).set_defaults(func=cmd_vscode_no_onboarding)
    sub.add_parser("ai-icon", help="copy the company file's icons.ai over each installed Agentic Works' AI activity bar "
                   "icon").set_defaults(func=cmd_ai_icon)
    running = sub.add_parser("vscode-running",
                             help="done when a `code` run now opens a window in a VS Code already running, skipped when not")
    running.add_argument("--code-version", required=True, metavar="VERSION",
                         help="what `code --version` says first: VS Code names the socket it is found by after it")
    running.set_defaults(func=cmd_vscode_running)
    made = sub.add_parser("vscode-profile", help="make a VS Code profile, with the user's settings copied in")
    made.add_argument("name")
    made.add_argument("--fill", action="store_true",
                      help="copy the user's settings into the profile, already made, where its own are blank")
    made.add_argument("--look", action="store_true",
                      help="with --fill: Agentic Works' look goes into the profile's blank settings with the user's")
    made.add_argument("--wait", type=float, default=0, metavar="SECONDS",
                      help="with --fill: give VS Code that long to make the profile, in a window opened on it")
    made.set_defaults(func=cmd_vscode_profile)
    return parser


def main(argv: Optional[List[str]] = None) -> int:
    global PROFILE
    args = build_parser().parse_args(argv)
    PROFILE = args.profile
    try:
        return args.func(args)
    except (OSError, sqlite3.Error, ValueError) as exc:
        print(f"agentic-works-install-helper: {exc}", file=sys.stderr)
        return EXIT_ERROR


if __name__ == "__main__":
    sys.exit(main())
AGENTIC_WORKS_INSTALL_HELPER_END
  return 0
  return 1
}

helper_path() {  # prints agentic-works-install-helper's path: $AGENTIC_WORKS_INSTALL_HELPER, the inlined one (a released script), or the one beside this script (the source tree)
  local here
  if [ -n "${AGENTIC_WORKS_INSTALL_HELPER:-}" ]; then
    printf '%s' "$AGENTIC_WORKS_INSTALL_HELPER"
    return 0
  fi
  # The inlined copy first: under `curl | bash`, $0 is `bash` and the sibling lookup would search the current directory.
  if [ -n "$INLINED_HELPER" ]; then
    printf '%s' "$INLINED_HELPER"
    return 0
  fi
  here=$(dirname "${BASH_SOURCE[0]:-$0}")
  [ -f "$here/agentic-works-install-helper" ] || return 1
  printf '%s' "$here/agentic-works-install-helper"
}

python_ok() {  # true when there is a python3 to run the helper with (in PYTHON); else PYTHON_WHY says why not
  local platform_python=${AGENTIC_WORKS_INSTALL_PLATFORM_PYTHON:-/usr/libexec/platform-python}
  local apple=${AGENTIC_WORKS_INSTALL_APPLE_PYTHON3:-/usr/bin/python3}
  PYTHON=${AGENTIC_WORKS_INSTALL_PYTHON3:-$(command -v python3 2> /dev/null)}
  PYTHON_WHY=""
  PYTHON_PLACEHOLDER=0
  # RHEL 8 has no python3 command until `dnf install python3`, but always has dnf's own Python 3.6, which the
  # helper runs on.
  if [ -z "$PYTHON" ] && [ "$OS" = rhel ] && [ -x "$platform_python" ]; then
    PYTHON=$platform_python
  fi
  if [ -z "$PYTHON" ]; then
    if [ "$OS" = macos ]; then
      PYTHON_WHY="python3 is not installed; install it (Homebrew: brew install python), then run the installer again"
    else
      PYTHON_WHY="python3 is not installed; install it, then run the installer again"
    fi
    return 1
  fi
  # macOS's /usr/bin/python3 is a shim that opens Apple's Command Line Tools install dialog when they're missing;
  # any other python3 (Homebrew's) is a real one.
  if [ "$OS" = macos ] && [ "$PYTHON" = "$apple" ] && ! xcode-select -p > /dev/null 2>&1; then
    PYTHON_WHY="python3 is not installed; run \`xcode-select --install\` (or brew install python), then run the"
    PYTHON_WHY="$PYTHON_WHY installer again"
    PYTHON=""
    PYTHON_PLACEHOLDER=1
    return 1
  fi
}

python_with_apples_tools() {  # after a python_ok that found only a Mac's placeholder: Apple's Command Line Tools, which
  # make it a python3 that runs. They come with Homebrew, whose installer has nothing to answer, when this run installs
  # Homebrew anyway (for gh; VS Code, its other reason, is there by the step that asks); else from Apple's own installer
  # window, waited for. True when python3 runs after (a dry run: when the install was printed); else PYTHON_WHY says why
  local why="python3 needs Apple's Command Line Tools"
  [ "$PYTHON_PLACEHOLDER" = 1 ] || return 1
  if [ "$HOMEBREW_STATE" = planned ] || { ! find_brew && ! skip_named github && ! have gh; }; then
    step_say "$why, which come with Homebrew"
    if ! ensure_homebrew; then
      PYTHON_WHY="$why, which come with Homebrew, which $(homebrew_failure); see $LOG"
      return 1
    fi
  else
    apple_installs_clt python3
    case $? in
      0) ;;
      2) PYTHON_WHY="finish the Command Line Tools install Apple opened, then run the installer again"
         return 1 ;;
      *) PYTHON_WHY="$why, and their install couldn't be started; see $LOG"
         return 1 ;;
    esac
  fi
  [ "$DRY_RUN" = 1 ] || python_ok
}

shell_words() {  # $* = words: as one line, a word with a space in single quotes ('Acme Works'), for a command shown
  local out="" w
  for w in "$@"; do
    case $w in *" "*) w="'$w'" ;; esac
    out="$out${out:+ }$w"
  done
  printf '%s' "$out"
}

run_helper() {  # $* = subcommand and its options: its stdout in HELPER_OUT; returns its exit status (0 done, 2 skipped, 1 error)
  local helper rc
  HELPER_OUT=""
  if ! helper=$(helper_path); then
    HELPER_OUT="agentic-works-install-helper isn't beside this script; run a released installer: $LATEST_INSTALLER"
    return 1
  fi
  # the settings and the layout go into --profile's profile; vscode-profile names its own
  case $1 in vscode-settings|vscode-layout) [ -z "$PROFILE" ] || set -- --profile "$PROFILE" "$@" ;; esac
  if [ "$DRY_RUN" = 1 ]; then
    step_say "\$ python3 $helper $(shell_words "$@")"
    return 0
  fi
  printf '$ %s %s %s\n' "$PYTHON" "$helper" "$(shell_words "$@")" >> "$LOG"
  # As root on Linux, the user data dir the code calls use.
  # On Linux, Agentic Works' own folders; as root on macOS-less Linux before them, the user data dir the code calls use.
  if [ "$OWN" = 1 ]; then
    HELPER_OUT=$(env "AGENTIC_WORKS_VSCODE_USER_DIR=$OWN_DATA/User" "AGENTIC_WORKS_VSCODE_EXTENSIONS_DIR=$OWN_EXT" \
      "AGENTIC_WORKS_TERMINAL_BIN=$OWN_ROOT/bin" "$PYTHON" "$helper" "$@" < /dev/null 2>> "$LOG")
  else
    HELPER_OUT=$(env ${CODE_DATA:+"AGENTIC_WORKS_VSCODE_USER_DIR=$CODE_DATA/User"} "$PYTHON" "$helper" "$@" \
      < /dev/null 2>> "$LOG")
  fi
  rc=$?
  case $rc in 0|2) ;; *) HELPER_OUT="" ;; esac  # an error's own words are in the log
  return "$rc"
}

look_step() {  # $1 = step name, $2 = label, $3 = helper subcommand (and options, split on spaces), $4 = done detail, $5 = failure detail
  local rc first rest line
  skipped "$1" "$2" && return 0
  step_begin "$2"
  if [ -n "$CLASH" ]; then
    step_end skipped "skipped — Agentic Works was not installed"
    return 0
  fi
  if ! python_ok; then
    step_end skipped "$PYTHON_WHY"
    return 0
  fi
  # shellcheck disable=SC2086  # $3 is a subcommand and its options
  run_helper $3
  rc=$?
  if [ "$DRY_RUN" = 1 ] && [ "$rc" = 0 ]; then
    step_end done "dry run"
    return 0
  fi
  case $rc in
    0) if [ "$HELPER_OUT" = "already set" ]; then step_end already; else step_end done "$4"; fi ;;
    2)  # the reason is the first line; the lines after it (settings to add by hand) go under the step
      first=${HELPER_OUT%%$'\n'*}
      rest=""
      [ "$first" = "$HELPER_OUT" ] || rest=${HELPER_OUT#*$'\n'}
      step_end skipped "${first%.}"
      if [ -n "$rest" ]; then
        while IFS= read -r line; do step_say "$line"; done <<< "$rest"
      fi ;;
    *) step_end failed "${HELPER_OUT:-$5}" ;;
  esac
}

apply_settings() {  # the look's keys, and codebase search when asked for, each only when absent; JSONC is left as it is
  local sub=vscode-settings settle=${AGENTIC_WORKS_INSTALL_SETTLE:-10} left
  [ "$CODEBASE_SEARCH" = 1 ] && sub="$sub --codebase-search"
  [ -n "$TEAMS_APP" ] && sub="$sub --teams-app $TEAMS_APP"  # checked by parse_args: no spaces in it
  if [ "$WINDOW_OPENED" = 1 ]; then
    # the window this run opened misses a settings.json written before it watches the file, about a second after it
    # opens, until the file is written again (see ensure_profile): written here, though nothing in it changes, and not
    # before the window has had its settle time (the steps since took most of it, or all)
    case $settle in ''|*[!0-9]*) settle=10 ;; esac
    left=$((WINDOW_AT + 10#$settle - SECONDS))  # 10#: 08 is eight, not a bad octal number
    [ "$left" -gt 0 ] || left=0
    sub="$sub --rewrite $left"
  fi
  look_step settings "Settings" "$sub" "added to settings.json" "couldn't write VS Code's settings; see $LOG"
  if [ "$STEP_RESULT" = done ] && [ "$HELPER_OUT" = "codebase search added" ]; then
    step_say "codebase search is on; to search by meaning too, run Agents: Install Codebase Search by Meaning in VS Code"
  fi
}

apply_icons() {  # the activity bar's icons, the vendor buttons on editor title bars and the panel's Debug Console, only on a VS Code never started (its state.vscdb has no layout yet)
  look_step icons "Icons" vscode-layout "activity bar, editor title bar and panel trimmed" "couldn't write the icon layout; see $LOG"
  case $STEP_RESULT:$HELPER_OUT in
    skipped:*"already has an icon layout"*) step_say "to hide an icon, a title-bar button or a panel tab yourself, right-click it" ;;
  esac
}

apply_ai_icon() {  # the company's own mark on the AI activity bar (note 101): its company file's icons.ai, copied over
  # each installed Agentic Works' own icon before VS Code starts. A line only when the helper says something, so none
  # without a company file or with one naming no mark; --skip icons leaves it out too.
  local company=${AGENTIC_WORKS_COMPANY_FILE:-$HOME/.config/agentic-works/company.json} rc
  skip_named icons && return 0
  [ -z "$CLASH" ] || return 0  # Agentic Works was not installed: the Icons line said so
  [ -f "$company" ] || return 0
  python_ok || return 0  # the Icons line said why; Agentic Works puts the mark in as it starts, shown from the start after
  if [ "$DRY_RUN" = 1 ]; then
    step_begin "AI icon"
    run_helper ai-icon
    step_end done "dry run"
    return 0
  fi
  run_helper ai-icon
  rc=$?
  [ "$rc" = 0 ] && [ -z "$HELPER_OUT" ] && return 0
  step_begin "AI icon"
  case $rc in
    0) if [ "$HELPER_OUT" = "already set" ]; then step_end already; else step_end done "$HELPER_OUT"; fi ;;
    2) step_end skipped "${HELPER_OUT%.}" ;;
    *) step_end failed "couldn't put the company's mark in; see $LOG" ;;
  esac
}

open_own() {  # Linux, a first install (or root): Agentic Works' own VS Code, through the launcher, on --folder (note 107)
  local -a args=()
  [ -n "$FOLDER" ] && [ "$TRUST_FOLDER" = 1 ] && args+=(--disable-workspace-trust)
  [ -z "$FOLDER" ] || args+=("$FOLDER")
  if [ "$DRY_RUN" = 1 ]; then
    printf "Would open Agentic Works' VS Code: \$ %s\n" "$(shell_words "$HOME/.local/bin/$SLUG" ${args[@]+"${args[@]}"})"
  elif [ "$AS_ROOT" = 1 ]; then
    printf 'Running as root, so VS Code is not opened. To start it: %s --no-sandbox\n' "${LAUNCHER:-$HOME/.local/bin/$SLUG}"
  else
    printf "Opening Agentic Works' VS Code.\n"
    if [ -n "$LAUNCHER" ] && [ -x "$LAUNCHER" ]; then
      run "$LAUNCHER" ${args[@]+"${args[@]}"}
    else  # the launcher step was skipped or failed
      code_cli ${args[@]+"${args[@]}"}
    fi || { printf "VS Code didn't open; open Agentic Works from your applications.\n"; return 0; }
    [ -z "$WINDOW_MARK" ] || : > "$WINDOW_MARK" 2>> "$LOG"
  fi
}

open_vscode() {  # VS Code, after a first install only: a plain start, which brings back any windows it had; once the checklist is done; not as root, nor with --no-open or --dry-run
  skip_named open && return 0
  [ "$NO_OPEN" = 1 ] && return 0
  [ -n "$CLASH" ] && return 0  # the run stopped at the standalone five
  [ "$WINDOW_OPENED" = 1 ] && return 0  # the window that made the profile is VS Code, opened
  find_code || [ "$DRY_RUN" = 1 ] || return 0
  if [ "$AS_ROOT" != 1 ] && [ "$AGENTIC_WORKS_FRESH" != 1 ]; then
    return 0  # an update or a repair: VS Code's windows stay as they are; the summary says when to reload them
  elif [ "$OWN" = 1 ]; then
    open_own
  elif [ "$DRY_RUN" = 1 ]; then
    printf 'Would open VS Code: $ %s\n' "$CODE"
  elif [ "$AS_ROOT" = 1 ]; then
    printf 'Running as root, so VS Code is not opened; open it as yourself.\n'
  else
    printf 'Opening VS Code.\n'
    code_cli || printf "VS Code didn't open; open it from your applications.\n"
  fi
}

# ---- sudo, the terminal, flags, main -------------------------------------------------------------------------

agentic_works_download_planned() {  # true when the Agentic Works step is going to download the .vsix: no Agentic Works yet, or an older one
  local current
  skip_named extension && return 1
  agentic_works_stamped || return 1
  find_code || return 0  # the VS Code step installs it first
  current=$(installed_version "$AGENTIC_WORKS_ID" "$(installed_extensions)") || return 0
  [ "$(version_cmp "$current" "$AGENTIC_WORKS_VERSION")" = lt ]
}

system_changes() {  # what the steps that are going to run add system-wide, one per line, in run order; or nothing
  local vscode=0 gh=0 ext=0 ms_repo=0 gh_repo=0 git=0 claude=0
  skip_named vscode || find_code || vscode=1
  # the claude step runs Anthropic's installer as the user (no sudo); only the curl it downloads with may be a system install
  skip_named claude || [ -n "$CLASH" ] || [ -e "$HOME/.local/bin/claude" ] || have claude || claude=1
  skip_named git || [ -n "$CLASH" ] || git_works || git=1
  skip_named github || have gh || gh=1
  if { [ "$vscode" = 1 ] || find_code; } && agentic_works_download_planned; then ext=1; fi
  case $OS in
    macos)  # VS Code and gh come through Homebrew, whose installer needs administrator rights
      if [ "$vscode$gh" != 00 ] && ! find_brew; then echo "Homebrew"; fi ;;
    ubuntu|debian)
      [ "$vscode" = 1 ] && ! apt_has_source "packages.microsoft.com/repos/code" && ms_repo=1
      [ "$gh" = 1 ] && ! apt_has_source "cli.github.com/packages" && gh_repo=1
      if ! have curl && [ "$ms_repo$gh_repo$ext$claude" != 0000 ]; then echo "curl and ca-certificates"; fi
      if [ "$ms_repo" = 1 ] && ! have gpg; then echo "gnupg"; fi
      [ "$ms_repo" = 1 ] && echo "Microsoft's VS Code package repository and its signing key"
      [ "$vscode" = 1 ] && echo "VS Code"
      [ "$git" = 1 ] && echo "git"
      [ "$gh_repo" = 1 ] && echo "GitHub's gh package repository and its signing key"
      [ "$gh" = 1 ] && echo "gh" ;;
    rhel|fedora)
      [ "$vscode" = 1 ] && printf '%s\n' "Microsoft's VS Code package repository and its signing key" "VS Code"
      if ! skip_named vscode && fedora_needs_ssl; then
        echo "OpenSSL 3 (Fedora, for VS Code's extension signature checks)"
      fi
      [ "$git" = 1 ] && echo "git"
      if [ "$gh" = 1 ] && [ "$OS" = rhel ]; then
        echo "GitHub's gh package repository and its signing key (with dnf's config-manager plugin)"
      fi
      [ "$gh" = 1 ] && echo "gh" ;;
  esac
  return 0
}

prepare_sudo() {  # one password prompt up front, only when something needs installing, after saying what
  local changes item
  [ "$DRY_RUN" = 1 ] && return 0
  [ -n "$SUDO" ] || return 0
  changes=$(system_changes)
  [ -n "$changes" ] || return 0
  printf 'Some installs need administrator rights; sudo may ask for your password. This run adds, system-wide:\n'
  while IFS= read -r item; do printf '  - %s\n' "$item"; done <<< "$changes"
  if ! sudo -v; then
    SUDO_FAILED=1
    printf 'sudo failed; the system installs below will fail too.\n'
  fi
}

open_tty() {  # fd 3 = the terminal the answers come from; TTY_OPEN=1 when there is one
  [ "$DRY_RUN" = 1 ] && return 0
  if { exec 3< "${AGENTIC_WORKS_INSTALL_TTY:-/dev/tty}"; } 2> /dev/null; then
    TTY_OPEN=1
  fi
}

usage() {
  cat <<EOF
agentic-works-install — VS Code with Agentic Works, on macOS and Linux desktops ($SUPPORTED)

  bash agentic-works-install.sh [options]

Options:
  --dry-run      print each command instead of running it
  --skip <step>  leave a step out; repeatable. Steps: $STEP_NAMES
  --yes          answer yes when asked to uninstall the standalone extensions Agentic Works replaces (needed with no
                 terminal)
  --no-open      don't open VS Code at the end
  --codebase-search
                 turn codebase search on in Claude and Codex tabs (off otherwise; Agentic Works' walkthrough offers it)
  --name <name>  Linux: the name of Agentic Works' own VS Code (its folders, command and icon); Agentic Works if not given
  --icon <file>  Linux: the picture its icon shows, a PNG or an SVG
  --profile <name>
                 macOS: install into the VS Code profile of that name, made when there is none (your settings, keybindings
                 and snippets copied in); your own profile is left as it is
  --folder <dir> with --profile: when VS Code is open, the window opened to make the profile opens on this folder
  --trust-folder with --folder: that window opens the folder trusted, not in Restricted Mode (where Agentic Works is
                 off); for a setup that made the folder itself
  --window-mark <file>
                 made when this run opened a VS Code window
  --teams-app <clientId>:<tenant>
                 sign Teams in with your company's own Microsoft app: its Application (client) ID, then the
                 Directory (tenant) ID or domain, from your IT team (added only when not already set)
  --help         this text

Environment:
  NO_COLOR       plain marks even on a terminal
EOF
}

teams_app_ok() {  # $1 = <clientId>:<tenant>: a GUID, a colon, then a GUID or a domain such as contoso.onmicrosoft.com
  local guid='[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}'
  local domain='([A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}'
  local re="^$guid:($guid|$domain)\$"
  [[ $1 =~ $re ]]
}

parse_args() {
  while [ $# -gt 0 ]; do
    case $1 in
      --dry-run) DRY_RUN=1 ;;
      --yes) YES=1 ;;
      --no-open) NO_OPEN=1 ;;
      --codebase-search) CODEBASE_SEARCH=1 ;;
      --no-codebase-search) ;;  # 0.2.0–0.3.3 asked, and this said no; it is off now unless asked for
      --teams-app)
        [ $# -ge 2 ] || { printf 'agentic-works-install: --teams-app needs <clientId>:<tenant>\n' >&2; exit 2; }
        teams_app_ok "$2" || {
          printf "agentic-works-install: --teams-app '%s' isn't <clientId>:<tenant> (a GUID, then a tenant GUID or a domain)\n" "$2" >&2
          exit 2
        }
        TEAMS_APP=$2
        shift ;;
      --name)
        [ $# -ge 2 ] && profile_name_ok "$2" && [ -n "$(slug_of "$2")" ] || {  # a letter or digit: its folders' name
          printf "agentic-works-install: --name needs a name: letters, digits, spaces, dots, dashes, underscores; up to 40; a letter or digit in it\n" >&2
          exit 2
        }
        NAME=$2
        shift ;;
      --icon)
        [ $# -ge 2 ] && [ -f "$2" ] && { png_file "$2" || svg_file "$2"; } || {
          printf 'agentic-works-install: --icon needs a PNG or SVG file that is there\n' >&2
          exit 2
        }
        case $2 in /*) ICON_FILE=$2 ;; *) ICON_FILE="$PWD/$2" ;; esac
        shift ;;
      --profile)
        [ $# -ge 2 ] && profile_name_ok "$2" || {
          printf "agentic-works-install: --profile needs a name: letters, digits, spaces, dots, dashes, underscores; up to 40\n" >&2
          exit 2
        }
        PROFILE=$2
        shift ;;
      --folder)
        [ $# -ge 2 ] && [ "${2#/}" != "$2" ] && [ -d "$2" ] || {
          printf 'agentic-works-install: --folder needs a folder that is there, as an absolute path\n' >&2
          exit 2
        }
        FOLDER=$2
        shift ;;
      --trust-folder) TRUST_FOLDER=1 ;;
      --window-mark)
        [ $# -ge 2 ] && [ "${2#/}" != "$2" ] || {
          printf 'agentic-works-install: --window-mark needs a file, as an absolute path\n' >&2
          exit 2
        }
        WINDOW_MARK=$2
        shift ;;
      --skip)
        [ $# -ge 2 ] || { printf 'agentic-works-install: --skip needs a step: %s\n' "$STEP_NAMES" >&2; exit 2; }
        case " $STEP_NAMES " in
          *" $2 "*) SKIPS="$SKIPS$2 " ;;
          *) printf "agentic-works-install: no step '%s'; steps: %s\n" "$2" "$STEP_NAMES" >&2; exit 2 ;;
        esac
        shift ;;
      --help|-h) usage; exit 0 ;;
      *) printf "agentic-works-install: unknown option '%s'\n\n" "$1" >&2; usage >&2; exit 2 ;;
    esac
    shift
  done
  if [ "$TRUST_FOLDER" = 1 ] && [ -z "$FOLDER" ]; then
    printf 'agentic-works-install: --trust-folder needs --folder\n' >&2
    exit 2
  fi
}

cleanup() {  # on exit: the log is kept, and named, only when a step failed and something was logged
  spinner_stop
  sudo_keepalive_stop
  [ -z "$VSIX_DIR" ] || rm -rf "$VSIX_DIR"
  [ -z "$INLINED_HELPER" ] || rm -f "$INLINED_HELPER"
  if [ "$N_FAIL" != 0 ] && [ -s "$LOG" ]; then
    printf 'Details of what failed: %s\n' "$LOG"
  elif [ "$LOG" != /dev/null ]; then
    rm -f "$LOG"
  fi
}

finish() {
  printf '\n'
  tally
  if [ "$DOCK_RESTART" = 1 ]; then  # a reload isn't enough (note 107's dock)
    printf 'Quit %s and start it again, to use Agentic Works %s with its windows under its own icon in the dock.\n' \
      "$NAME" "$AGENTIC_WORKS_VERSION"
    return 0
  fi
  if [ "$RELOAD_VSCODE" = 1 ] && [ "$OWN" = 1 ]; then
    printf "Reload Agentic Works' windows to use Agentic Works %s.\n" "$AGENTIC_WORKS_VERSION"
    return 0
  fi
  [ "$RELOAD_VSCODE" != 1 ] || printf "Reload your local VS Code windows to use Agentic Works %s; Remote windows aren't affected.\n" "$AGENTIC_WORKS_VERSION"
}

main() {  # the steps, in order
  parse_args "$@"
  LOG=$(mktemp "${TMPDIR:-/tmp}/agentic-works-install-log.XXXXXX")
  trap cleanup EXIT
  trap 'exit 130' INT  # through the EXIT trap, so an interrupted run leaves no download behind
  trap 'exit 143' TERM
  write_inlined_helper || INLINED_HELPER=""
  printf 'agentic-works-install — VS Code with Agentic Works%s\n\n' "$([ "$DRY_RUN" = 1 ] && echo ' (dry run)')"
  check_platform
  set_own_folders
  prepare_sudo
  open_tty
  ensure_vscode
  ensure_path
  ensure_profile
  check_standalone
  ensure_agentic_works
  ensure_launcher
  ensure_companions
  ensure_claude
  ensure_git
  ensure_github
  ensure_homebrew_path
  apply_settings
  apply_icons
  apply_ai_icon
  finish
  open_vscode
  [ "$N_FAIL" = 0 ]
}

[ "${AGENTIC_WORKS_INSTALL_NO_MAIN:-}" = 1 ] || main "$@"
