#!/bin/bash

# Everything below needs bash: `local`, `[[ ]]`, and the `set -o pipefail` on
# the next line. Piped into a POSIX shell — `curl ... | sh`, and /bin/sh is
# dash on Debian/Ubuntu — that `set` aborts on line 1 with
#   sh: set: Illegal option -o pipefail
# before the error reporting below is even defined, so the failure is opaque
# to the user and invisible to us. `| sh` one-liners are published in places we
# can't edit, so hand over to bash rather than trusting the shebang.
if [ -z "${BASH_VERSION:-}" ]; then
  if command -v bash > /dev/null 2>&1; then
    # Saved to a file: just re-run it. Piped: this script has already been
    # consumed from stdin and cannot be rewound, so refetch it under bash.
    case "$0" in
      */install.sh | install.sh) exec bash "$0" "$@" ;;
    esac
    # Hardened by hand rather than via CURL_TLS_ARGS: this runs under /bin/sh
    # before the bash-only preamble that defines the array (see #165).
    exec bash -c 'curl -fsSL --proto "=https" --proto-redir "=https" --tlsv1.2 --max-redirs 3 https://install.squirrelscan.com/install.sh | bash'
  fi
  echo "Error: the squirrelscan installer requires bash, and none was found." >&2
  echo "  Install bash, or grab a binary from https://github.com/squirrelscan/squirrelscan/releases" >&2
  exit 1
fi

set -euo pipefail

# Nothing the installer creates (the bin directory, ~/.squirrel, the binary, the temp
# directory) may be group or world writable, whatever umask it inherited: a permissive one
# (0000 in some containers and CI images) would leave a world-writable directory and binary
# on PATH. Only ever tightened: a stricter umask (077) is kept.
umask "$(printf '%04o' "$((0$(umask) | 022))")"

# squirrelscan installer
# Usage: curl -fsSL https://install.squirrelscan.com/install.sh | bash
# Or: curl -fsSL https://raw.githubusercontent.com/squirrelscan/squirrelscan/main/install.sh | bash
#
# Environment variables:
#   SQUIRREL_VERSION   - Pin to specific version (e.g., v0.0.15)
#   SQUIRREL_CHANNEL   - Release channel: stable or beta (default: stable)
#   SQUIRREL_BIN_DIR   - Override bin directory for symlink
#   SQUIRREL_NO_MODIFY_PATH - Never edit a shell profile (or GITHUB_PATH);
#                        print the PATH instructions instead. Any value but
#                        empty, 0 or false enables it.
#   SQUIRREL_FORCE_MIRROR - Skip github.com and download from
#                        install.squirrelscan.com (for networks that block
#                        GitHub). Any value but empty, 0 or false enables it.
#   GITHUB_TOKEN       - GitHub token to avoid API rate limits (optional)
#   NO_TELEMETRY       - Send no failure report (any defined value, even empty);
#                        DO_NOT_TRACK=1 does the same. Sourcing this file never
#                        reports either (see INSTALLER_INVOCATION).

REPO="squirrelscan/squirrelscan"
CERT_IDENTITY="https://github.com/squirrelscan/squirrelscan/.github/workflows/release.yml@refs/heads/main"

# Pinned release signing keys (squirrelscan/repo#5032), rendered from
# release-keys.json. A release is accepted when EITHER a pinned, non-revoked
# key signed it OR its GitHub attestation verifies; see verify_release_signature.
# Both slots empty means the signature path is off and nothing changes.
# BEGIN GENERATED RELEASE KEYS (scripts/sync-install-header.ts, from release-keys.json; do not edit)
RELEASE_KEY_CURRENT_ID='3d10cf3775665622'
RELEASE_KEY_CURRENT_PEM='-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEN8K5cMpCjrfRAEv94Fiic1a65ED6
wzfEsN/5YD0EUAJrlIL76/L4KPU+L6/Oloiua4UYWu9bK5YFBvKQpsn7FQ==
-----END PUBLIC KEY-----'
RELEASE_KEY_NEXT_ID=''
RELEASE_KEY_NEXT_PEM=''
RELEASE_KEYS_REVOKED=''
RELEASE_FIRST_SIGNED_VERSION='0.0.190-beta.1'
# END GENERATED RELEASE KEYS

# Transport hardening for every curl this script runs. curl's own defaults will
# happily follow a redirect from https to plain http and will negotiate whatever
# TLS version the local build still allows, so pin both: --proto bounds the
# scheme of the initial request, --proto-redir bounds it again on every hop
# (the two are separate settings — one does not imply the other), --tlsv1.2 sets
# the floor, and --max-redirs bounds the chain. The binary is checksum-verified
# against the manifest, but the metadata fetches and the bash re-exec have no
# integrity protection beyond the transport itself (#165).
# --tlsv1.2 is the youngest of the four and landed in curl 7.34 (2013), below
# every platform we support: the oldest realistic holdout is RHEL 7 at curl
# 7.29, whose glibc 2.17 is already under the bun standalone binary's floor.
# An unsupported option exits 2 with "option ...: is unknown", which
# fetch_with_retry discards, so it would read as three failed download retries.
CURL_TLS_ARGS=(--proto '=https' --proto-redir '=https' --tlsv1.2 --max-redirs 3)

# Detect if stdout is a terminal for colors
if [ -t 1 ]; then
  RED='\033[0;31m'
  GREEN='\033[0;32m'
  YELLOW='\033[0;33m'
  BLUE='\033[0;34m'
  NC='\033[0m'
else
  RED='' GREEN='' YELLOW='' BLUE='' NC=''
fi

# log, warn and info are progress chatter and must never abort the install: under `set -e` a
# failed write to stderr (closed or broken pipe, as in some wrappers and agent shells) would
# otherwise end the run at the log call and be reported under whatever step was current (#3554).
log() { echo -e "${GREEN}==>${NC} $1" >&2 || true; }
warn() { echo -e "${YELLOW}Warning:${NC} $1" >&2 || true; }
# error <message> [detail]
# `message` is shown to the user AND carried in the failure report, where it is
# clamped to ERROR_LINE_MAX. A report's `error_line` comes only from error() (LAST_ERROR_MSG or the
# ERROR_MSG_FILE fallback), the signal traps, or the curl-exit fallback in report_on_exit ("curl exit
# <code> reaching <host>" when no message was recorded): log, info and warn lines never reach it.
# `detail` is remediation text shown to the user only: a long guidance block passed as `message` would push the actual error
# out of the report's `error_line`.
error() {
  echo -e "${RED}Error:${NC} $1" >&2
  if [ -n "${2:-}" ]; then
    echo -e "$2" >&2
  fi
  LAST_ERROR_MSG="$1"
  # Also persist to a file: error() often runs inside a command-substitution
  # subshell (e.g. version=$(get_latest_version)), where the LAST_ERROR_MSG
  # assignment can't reach the parent that runs the EXIT trap.
  [ -n "${ERROR_MSG_FILE:-}" ] && printf '%s' "$1" >"$ERROR_MSG_FILE" 2>/dev/null || true
  exit 1
}
info() { echo -e "${BLUE}::${NC} $1" >&2 || true; }

# --- Failure reporting ----------------------------------------------------
# On failure, fire a tiny anonymous report to the installer worker (→ Sentry)
# so we can see when installs break in the field. Strictly opt-out via
# NO_TELEMETRY or DO_NOT_TRACK=1 (mirrors the CLI, apps/cli/src/self/telemetry.ts), fire-and-
# forget (never blocks or fails the install), and carries only coarse context
# (os/arch/step/exit code) — never paths, env, hostname, or secrets. #1013
# v2 adds `error_output` — the tail of the failing command's own output (#1538).
# v3 adds `version` (the release being installed) and, on Linux, `libc`.
# v4 adds, for a curl network failure, `host` (one of OUR hosts, else "custom"; never a path, query
# or credentials) and `ip_family` (v4, v6 or unknown: the family the connection was attempted on),
# and the step before the first named one is `startup`, not `init` (#1681).
INSTALLER_REPORT_VERSION="4"
# The release being installed, bare ("0.0.73"), set as soon as it is known
# (pinned or resolved). Empty before that, and then the report omits the field.
INSTALLER_RELEASE_VERSION=""
ERROR_ENDPOINT="${SQUIRREL_ERROR_ENDPOINT:-https://install.squirrelscan.com/error}"
# How this file is being run: `stream` (piped to bash, or bash -c "$(curl ...)"), `file` (bash install.sh) or
# `sourced`. A sourced copy is a test harness or a wrapper borrowing the functions, not a user installing: its
# failures are not install failures, and 134 reports of one made-up shape ((exit 7) || report_on_exit) reached
# production that way (#5020). report_error stays silent for it; SQUIRREL_REPORT_WHEN_SOURCED=1 is the
# contract tests' switch for the payload tests that source the preamble on purpose.
INSTALLER_INVOCATION="stream"
if [ -n "${BASH_SOURCE[0]:-}" ]; then
  if [ "${BASH_SOURCE[0]}" = "$0" ]; then INSTALLER_INVOCATION="file"; else INSTALLER_INVOCATION="sourced"; fi
fi
# Release metadata (latest version per channel) — R2-backed, no rate limits.
RELEASES_ENDPOINT="${SQUIRREL_RELEASES_ENDPOINT:-https://install.squirrelscan.com/releases}"
# Release assets, mirrored through our own origin. A GitHub release-asset URL
# redirects to githubusercontent.com (objects.* historically, release-assets.*
# today), which some networks cannot reach: the metadata fetch above succeeds
# and the binary download then fails on every retry, forever (#2064). Every
# asset therefore has two sources.
DOWNLOAD_ENDPOINT="${SQUIRREL_DOWNLOAD_ENDPOINT:-https://install.squirrelscan.com/dl}"
ERROR_LINE_MAX=200
# Chars of captured command output carried in a report. The worker clamps again.
ERROR_OUTPUT_MAX=1000
# The step before main() names its first one. Never `init`: a report with that step, as INSTALLER-WORKER-7
# had, cannot be told from a run of a script that predates the named steps (#1681).
CURRENT_STEP="startup"
LAST_ERROR_MSG=""
# Captured stdout/stderr of the step that failed, when we ran it under tee.
LAST_ERROR_OUTPUT=""
# Real exit code of a failed sub-command, when it isn't the one error() exits with.
LAST_ERROR_CODE=""
# The last command that failed under `set -e` (its bare name, never arguments or paths) and its line, recorded by
# the ERR trap, so a report with no message can still say what died.
FAILED_CMD=""
FAILED_LINE=""
TMPDIR_TO_CLEAN=""
# A second staging directory, under ~/.squirrel/tmp, used when the system temp dir is noexec.
STAGE_TO_CLEAN=""
# A background child (a download, a retry pause) the exit trap ends if the installer is signalled mid-wait.
CHILD_PID=""
# Survives command-substitution subshells where LAST_ERROR_MSG can't (see error()).
ERROR_MSG_FILE="$(mktemp 2>/dev/null || true)"
# Where the last request went, kept in a file as well as in LAST_FETCH_HOST: a fetch inside a
# command substitution (version=$(get_latest_version)) sets the variable in a subshell the exit trap
# never sees, which is how a report came to say "an unknown host" for a request that had been made.
FETCH_HOST_FILE="$(mktemp 2>/dev/null || true)"

# Make a value safe inside a JSON string: keep only printable ASCII (drops
# control chars incl. ESC from ANSI colour codes, AND non-ASCII bytes — either
# would make the JSON invalid and the worker would reject the whole report),
# then escape backslashes and double-quotes.
json_escape() {
  printf '%s' "$1" | LC_ALL=C tr -cd '\40-\176' | sed -e 's/\\/\\\\/g' -e 's/"/\\"/g'
}

# Reduce a value to printable ASCII (control chars incl. newlines AND non-ASCII
# bytes → space) BEFORE truncating, so `cut -c` can't split a multibyte char
# into invalid UTF-8. Scrub $HOME → '~' so no local path leaks. Command output
# keeps its TAIL (that's where the error is); a message keeps its head. The
# worker re-clamps and redacts too.
scrub_for_report() {
  local text="$1" max="$2" keep_tail="${3:-head}" scrubbed tilde="~"
  if [ -z "$text" ]; then
    return 0
  fi
  scrubbed=$(printf '%s' "$text" | LC_ALL=C tr -c '\40-\176' ' ')
  if [ -n "${HOME:-}" ]; then
    scrubbed=${scrubbed//"$HOME"/$tilde}
  fi
  if [ "$keep_tail" = tail ] && [ "${#scrubbed}" -gt "$max" ]; then
    printf '%s' "${scrubbed:${#scrubbed}-max}"
  else
    printf '%s' "$scrubbed" | cut -c"1-$max"
  fi
}

# Detect libc (glibc vs musl)
detect_libc() {
  # Method 1: Check for musl loader (most reliable)
  if ls /lib/ld-musl-*.so.1 >/dev/null 2>&1; then
    echo "-musl"
    return
  fi

  # Method 2: Check Alpine release file
  if [ -f /etc/alpine-release ]; then
    echo "-musl"
    return
  fi

  # Method 3: ldd version string
  if command -v ldd >/dev/null 2>&1; then
    if ldd --version 2>&1 | grep -qi musl; then
      echo "-musl"
      return
    fi
  fi

  # Default: glibc (no suffix)
  echo ""
}

report_error() {
  local step="$1" code="$2" line="${3:-}" output="${4:-}"
  # A report always names a step: `init` (the old default) and an empty one read as `startup` (#1681).
  case "$step" in "" | init) step=startup ;; esac
  # Presence of NO_TELEMETRY disables reporting, including an explicitly empty
  # value; so does DO_NOT_TRACK=1 or true (mirrors the CLI).
  [ "${NO_TELEMETRY+x}" = x ] && return 0
  case "${DO_NOT_TRACK:-}" in 1 | [Tt][Rr][Uu][Ee]) return 0 ;; esac
  [ "$INSTALLER_INVOCATION" = sourced ] && [ -z "${SQUIRREL_REPORT_WHEN_SOURCED:-}" ] && return 0
  command -v curl >/dev/null 2>&1 || return 0

  local os arch scrubbed="" scrubbed_output="" version_field="" libc_field=""
  os=$(uname -s 2>/dev/null | tr '[:upper:]' '[:lower:]')
  arch=$(uname -m 2>/dev/null)

  if [ -n "$INSTALLER_RELEASE_VERSION" ]; then
    version_field=$(printf ',"version":"%s"' "$(json_escape "${INSTALLER_RELEASE_VERSION#v}")")
  fi
  # A fact, not a guess: the worker would otherwise resolve a musl report to the
  # glibc platform. Same detection the installer itself uses to pick the asset.
  if [ "$os" = linux ]; then
    case "$(detect_libc)" in
      -musl) libc_field=',"libc":"musl"' ;;
      *) libc_field=',"libc":"glibc"' ;;
    esac
  fi

  scrubbed=$(scrub_for_report "$line" "$ERROR_LINE_MAX")
  # The failing command's own stdout/stderr: without it a self_install failure
  # carried an exit code and nothing else (#1538).
  scrubbed_output=$(scrub_for_report "$output" "$ERROR_OUTPUT_MAX" tail)

  local payload
  payload=$(printf '{"script":"sh","script_version":"%s","channel":"%s","os":"%s","arch":"%s"%s%s,"step":"%s","exit_code":%s,"error_line":"%s","error_output":"%s"}' \
    "$(json_escape "$INSTALLER_REPORT_VERSION")" \
    "$(json_escape "${SQUIRREL_CHANNEL:-stable}")" \
    "$(json_escape "$os")" \
    "$(json_escape "$arch")" \
    "$libc_field" \
    "$version_field" \
    "$(json_escape "$step")" \
    "${code:-1}" \
    "$(json_escape "$scrubbed")" \
    "$(json_escape "$scrubbed_output")")

  # A curl network failure also says where it was going and on which IP family (#1681): the host is
  # one of ours or "custom", and the family is probed in the detached reporter below, so the install
  # never waits for it.
  local host=""
  if is_curl_network_code "${code:-1}" || is_curl_network_code "$LAST_CURL_CODE"; then
    host=$(reportable_host "$LAST_FETCH_HOST")
  fi

  # Fire-and-forget: run the POST in a DETACHED subshell so it never blocks the
  # installer. `( cmd & )` backgrounds the group and lets the subshell exit
  # immediately (non-blocking); the group is reparented to init so it still gets to
  # finish after the script exits. Tight timeouts are the backstop; stdio
  # discarded so a closed pipe can't SIGPIPE it.
  ( {
      if [ -n "$host" ]; then
        ip_family=unknown
        [ "$host" != custom ] && ip_family=$(probe_ip_family "$host")
        payload="${payload%?},\"host\":\"$(json_escape "$host")\",\"ip_family\":\"$ip_family\"}"
      fi
      curl "${CURL_TLS_ARGS[@]}" -fsS -m 3 --connect-timeout 2 -X POST \
        -H 'Content-Type: application/json' \
        --data "$payload" "$ERROR_ENDPOINT"
    } >/dev/null 2>&1 & ) 2>/dev/null || true
}

# --- Killed-process diagnosis ---------------------------------------------
# A shell reports a signal-killed child as 128+signal: 137 is SIGKILL, 143 is
# SIGTERM. In the field 137 is the kernel OOM-killer taking out the bun
# standalone binary on a small VPS or a memory-capped container. It leaves
# NOTHING on stdout/stderr, so the exit code is the only evidence there is, and
# a generic "failed with exit code 137" sent users back to retry it unchanged.
SELF_INSTALL_KILL_CODES="137 143"
# Reported instead of `self_install` for these codes. The Sentry fingerprint is
# (script, step) with the exit code only in event data, so without a distinct
# step every OOM kill groups into the same issue as a real self-install bug.
SELF_INSTALL_KILLED_STEP="self_install_killed"

# Indirected so the tests can point the probe at fixtures instead of the real
# kernel interfaces. SQUIRREL_ERROR_ENDPOINT and SQUIRREL_RELEASES_ENDPOINT
# above are seamed the same way, but since #165 both are HTTPS-only: curl
# refuses a plain-http override with "Protocol http disabled", so a local
# stand-in has to serve TLS that the running curl already trusts.
CGROUP_ROOT="${SQUIRREL_CGROUP_ROOT:-/sys/fs/cgroup}"
PROC_SELF_CGROUP="${SQUIRREL_PROC_SELF_CGROUP:-/proc/self/cgroup}"
PROC_MEMINFO="${SQUIRREL_PROC_MEMINFO:-/proc/meminfo}"
# Above this, a "limit" is a not-configured sentinel rather than a real cap:
# cgroup v1 parks an uncapped controller at PAGE_COUNTER_MAX (~8 EiB).
CGROUP_LIMIT_SANITY_MAX=1099511627776 # 1TiB

is_uint() {
  case "${1:-}" in
    "" | *[!0-9]*) return 1 ;;
    *) return 0 ;;
  esac
}

# True when digit-string $1 exceeds digit-string $2, compared WITHOUT bash
# arithmetic: cgroup limits routinely exceed a signed 64-bit integer (v1 writes
# UINT64_MAX for "unlimited" on many kernels), and `[ "$v" -gt ... ]` wraps on
# those, so an unlimited controller would read as a real 16-exabyte cap. Equal
# length digit strings compare correctly lexically.
uint_gt() {
  # Digits collate out of order in a handful of locales, and this decides
  # whether a cap is real, so pin the comparison.
  local LC_ALL=C
  local a="${1#"${1%%[!0]*}"}" b="${2#"${2%%[!0]*}"}"
  a="${a:-0}"
  b="${b:-0}"
  if [ "${#a}" -ne "${#b}" ]; then
    [ "${#a}" -gt "${#b}" ]
    return
  fi
  [[ "$a" > "$b" ]]
}

# This process's path within a cgroup hierarchy, selected by an awk program
# over /proc/self/cgroup. Empty when the hierarchy isn't in use.
cgroup_rel_path() {
  local program="$1"
  if [ -r "$PROC_SELF_CGROUP" ]; then
    awk -F: "$program" "$PROC_SELF_CGROUP" 2>/dev/null || true
  fi
}

# The kernel only ever writes an absolute, traversal-free path here, but this
# string is about to be concatenated into a filesystem read and fed to a loop
# that shortens it, so anything else is refused rather than followed.
is_safe_cgroup_rel() {
  case "${1:-}" in
    "") return 0 ;;
    *//* | */../* | */.. | */./* | */.) return 1 ;;
    /*) return 0 ;;
    *) return 1 ;;
  esac
}

# Headroom under one cgroup memory cap, in MiB.
#   prints a number, returns 0 -> a real cap, and this is what's left under it
#   prints nothing, returns 0 -> no cap here; the caller may look elsewhere
#   returns 1                 -> a cap exists but can't be read; the caller must
#                                stay SILENT rather than quote the host's memory
cgroup_headroom_mib() {
  local limit_file="$1" usage_file="$2" limit usage
  if [ ! -f "$limit_file" ]; then
    return 0
  fi
  limit=$(cat "$limit_file" 2>/dev/null || true)
  if ! is_uint "$limit" || uint_gt "$limit" "$CGROUP_LIMIT_SANITY_MAX"; then
    # A literal "max" (v2) or a sentinel (v1) is a genuine "uncapped"; anything
    # else here is a value we failed to understand, which is not the same thing.
    if [ "$limit" = "max" ] || is_uint "$limit"; then
      return 0
    fi
    return 1
  fi
  usage=$(cat "$usage_file" 2>/dev/null || true)
  if ! is_uint "$usage"; then
    return 1
  fi
  # Clamp rather than underflow: usage sits at or above the limit at the moment
  # of an OOM kill, and "0" is the true answer there. Compared without
  # arithmetic for the same overflow reason as the limit above; past this point
  # both values are under the sanity bound, so the subtraction is safe.
  if ! uint_gt "$limit" "$usage"; then
    printf '0'
  else
    printf '%s' "$(((limit - usage) / 1048576))"
  fi
}

# Walks from this process's own cgroup up to the mount root: a limit on an
# ancestor (a systemd slice's MemoryMax, typically) binds exactly as hard as one
# on the leaf, and the leaf is very often uncapped underneath it. The tightest
# headroom wins, and a cap anywhere in the chain that we cannot read makes the
# whole answer unknown rather than optimistic.
cgroup_tree_headroom_mib() {
  local base="$1" limit_name="$2" usage_name="$3" rel="$4"
  local best="" headroom dir previous
  while :; do
    dir="${base}${rel}"
    if headroom=$(cgroup_headroom_mib "$dir/$limit_name" "$dir/$usage_name"); then
      if [ -n "$headroom" ] && { [ -z "$best" ] || [ "$headroom" -lt "$best" ]; }; then
        best="$headroom"
      fi
    else
      return 1
    fi
    if [ -z "$rel" ]; then
      break
    fi
    # is_safe_cgroup_rel guarantees this shortens, but a loop that walks a
    # string from a file gets an explicit termination guard regardless: hanging
    # the installer would be a worse bug than the one being fixed here.
    previous="$rel"
    rel="${rel%/*}"
    if [ "$rel" = "$previous" ]; then
      break
    fi
  done
  printf '%s' "$best"
}

# Memory this process could still get, in MiB, or empty when we can't say --
# every caller must handle empty. cgroups are consulted FIRST, and a cap we can
# see but not read suppresses the answer entirely, because /proc/meminfo
# describes the HOST inside a container: it would cheerfully report gigabytes
# free moments after the kernel killed us for passing a 256MB cap.
available_memory_mib() {
  local rel headroom kib

  # cgroup v2: a single "0::<path>" line, relative to the v2 mount.
  rel=$(cgroup_rel_path '$1 == "0" { print $3; exit }')
  if [ -n "$rel" ] && is_safe_cgroup_rel "$rel"; then
    if headroom=$(cgroup_tree_headroom_mib \
      "$CGROUP_ROOT" memory.max memory.current "${rel%/}"); then
      if [ -n "$headroom" ]; then
        printf '%s' "$headroom"
        return 0
      fi
    else
      return 0
    fi
  fi

  # cgroup v1: "<n>:memory:<path>", under the memory controller's own mount.
  rel=$(cgroup_rel_path '$2 ~ /(^|,)memory(,|$)/ { print $3; exit }')
  if [ -n "$rel" ] && is_safe_cgroup_rel "$rel"; then
    if headroom=$(cgroup_tree_headroom_mib \
      "$CGROUP_ROOT/memory" memory.limit_in_bytes memory.usage_in_bytes "${rel%/}"); then
      if [ -n "$headroom" ]; then
        printf '%s' "$headroom"
        return 0
      fi
    else
      return 0
    fi
  fi

  # Demonstrably uncapped, so the host figure is the honest one. MemAvailable,
  # not MemFree: MemFree ignores reclaimable page cache and reads far too low.
  if [ -r "$PROC_MEMINFO" ]; then
    kib=$(awk '/^MemAvailable:/ { print $2; exit }' "$PROC_MEMINFO" 2>/dev/null || true)
    if is_uint "$kib"; then
      printf '%s' "$((kib / 1024))"
    fi
  fi
  return 0
}

# The step name reported for a self-install exit code: signal deaths get their
# own bucket, everything else keeps reporting as `self_install` (#1654).
self_install_step_for_code() {
  local code="$1" kill_code
  for kill_code in $SELF_INSTALL_KILL_CODES; do
    if [ "$code" = "$kill_code" ]; then
      printf '%s' "$SELF_INSTALL_KILLED_STEP"
      return 0
    fi
  done
  printf 'self_install'
}

# Names the signal behind a 128+n exit code, for the error line.
signal_name_for_code() {
  case "${1:-}" in
    137) printf 'SIGKILL' ;;
    143) printf 'SIGTERM' ;;
    *) printf 'signal %s' "$((${1:-128} - 128))" ;;
  esac
}

# The headline for a signal death. Only SIGKILL gets to assert memory: SIGTERM
# arrives from `timeout` wrappers and cancelled CI jobs too, and this whole fix
# exists because a confidently wrong diagnosis wastes the user's time.
self_install_kill_headline() {
  local code="$1" signal
  signal=$(signal_name_for_code "$code")
  if [ "$code" = 137 ]; then
    printf 'Self install was killed by the system (exit %s, %s), most likely out of memory' \
      "$code" "$signal"
  else
    printf 'Self install was stopped by a signal before it finished (exit %s, %s)' \
      "$code" "$signal"
  fi
}

# Remediation block for a signal-killed self install. Printed as error()'s
# `detail`, so it never crowds the reported error_line. Only SIGKILL gets the
# out-of-memory diagnosis and the swap recipe: SIGTERM arrives from `timeout`
# wrappers, supervisors and cancelled CI jobs at least as often, and telling
# those users to add swap would send them off fixing the wrong machine.
self_install_kill_guidance() {
  local code="$1" mib="" cause=""
  # Contained: this only ever runs on an already-failing path, so a probe that
  # trips must cost the user a memory figure, never the guidance itself.
  mib=$( (available_memory_mib) 2>/dev/null || true)

  if [ "$code" = 137 ]; then
    cause="  The download itself was fine: the binary passed its checksum, then the
  system killed it partway through installing. On a small VPS or a
  memory-capped container that is almost always the out-of-memory killer."
    if [ -n "$mib" ]; then
      cause="${cause}
  Memory available right now: ${mib} MB"
    fi
    printf '%s' "${cause}

  Give the machine more memory, then re-run this installer:
    Add 1GB of swap (usually the quickest fix on a VPS):
      sudo fallocate -l 1G /swapfile && sudo chmod 600 /swapfile
      sudo mkswap /swapfile && sudo swapon /swapfile
    Or resize the machine, or raise the container memory limit, to 1GB or more.

  If you cannot add memory, download the binary directly and put it on your
  PATH by hand:
    https://github.com/${REPO}/releases"
    return 0
  fi

  cause="  The download itself was fine: the binary passed its checksum, then
  something outside the installer stopped it partway through. Usually that is a
  timeout wrapper, a process supervisor, a cancelled job, or a memory limit."
  if [ -n "$mib" ]; then
    cause="${cause}
  Memory available right now: ${mib} MB"
  fi
  printf '%s' "${cause}

  Re-run the installer without a timeout or job limit around it. If it keeps
  happening, download the binary directly and put it on your PATH by hand:
    https://github.com/${REPO}/releases"
}

# --- By-hand install after a killed self install ---------------------------
# `self install` does trivial file work: copy the binary under
# ~/.squirrel/releases/<version>/, symlink it from bin_dir, record the bin dir
# in settings.json. When the kernel kills the binary before it gets to that
# work, do it here in bash, which costs nothing, then check the binary can
# actually run. A machine that cannot run `squirrel --version` gets a distinct
# step, a memory figure, and the concrete state of the install (#2023).
VERIFY_BINARY_STEP="verify_binary"
VERIFY_BINARY_KILLED_STEP="verify_binary_killed"

verify_binary_step_for_code() {
  local code="$1" kill_code
  for kill_code in $SELF_INSTALL_KILL_CODES; do
    if [ "$code" = "$kill_code" ]; then
      printf '%s' "$VERIFY_BINARY_KILLED_STEP"
      return 0
    fi
  done
  printf '%s' "$VERIFY_BINARY_STEP"
}

# The CLI reads settings from $HOME/.squirrel (apps/cli/src/self/paths.ts).
squirrel_home_dir() {
  printf '%s/.squirrel' "$HOME"
}

# True when a value can be dropped into a JSON string verbatim: printable
# ASCII with no quote or backslash. Anything else is left unrecorded rather
# than mangled — a wrong install_bin_dir sends every later `self update` to
# the wrong link (#293), a missing one falls back to the default.
is_plain_json_string() {
  # [:print:] under LC_ALL=C is exactly ASCII 0x20-0x7E (bash 3.2 does not
  # take a quoted space inside a bracket range, so no ' '-~ here).
  case "$(LC_ALL=C printf '%s' "$1" | LC_ALL=C tr -d '[:print:]')" in
    ?*) return 1 ;;
  esac
  case "$1" in
    *'"'*|*'\'*|'') return 1 ;;
  esac
  return 0
}

# Record install_bin_dir in settings.json the way `self install` does, so a
# later `self update` flips the link this installer created. Merges into an
# existing file (jq when available, a keyed substitution otherwise) and writes
# a fresh one when absent: the CLI parses settings as a partial, so a file
# holding only install_bin_dir is valid. Never fatal: prints a warning and
# returns 0, the install itself is already in place.
record_install_bin_dir() {
  local settings="$1" bin_dir="$2" tmp content
  if ! is_plain_json_string "$bin_dir"; then
    warn "Not recording the bin directory in $settings (unusual characters in the path)"
    return 0
  fi
  tmp="$settings.tmp.$$"
  if [ ! -f "$settings" ]; then
    mkdir -p "$(dirname "$settings")" 2>/dev/null || true
    if printf '{\n  "install_bin_dir": "%s"\n}\n' "$bin_dir" >"$tmp" 2>/dev/null \
        && chmod 600 "$tmp" 2>/dev/null && mv -f "$tmp" "$settings" 2>/dev/null; then
      return 0
    fi
    rm -f "$tmp" 2>/dev/null
    warn "Could not write $settings; run 'squirrel self install --bin-dir $bin_dir' later"
    return 0
  fi
  if [ "${USE_JQ:-false}" = true ]; then
    if jq --arg d "$bin_dir" '.install_bin_dir = $d' "$settings" >"$tmp" 2>/dev/null \
        && [ -s "$tmp" ] && chmod 600 "$tmp" 2>/dev/null && mv -f "$tmp" "$settings" 2>/dev/null; then
      return 0
    fi
    rm -f "$tmp" 2>/dev/null
  fi
  # No jq (or jq failed). Two shapes are handled by hand, neither through
  # pattern replacement (bash's ${var/../..} and sed both give `&` and `\` in
  # the path a meaning, and bash 3.2 mangles a `{` in the replacement): a
  # missing key is inserted after the opening brace, and a `null` value is
  # filled in. Anything else already recorded is left exactly as it is.
  content=$(cat "$settings" 2>/dev/null) || content=""
  local lead rest before after trimmed body
  lead="${content%%'{'*}"
  if [ "$lead" = "$content" ] || [ -n "${lead//[[:space:]]/}" ]; then
    warn "Could not update $settings; run 'squirrel self install --bin-dir $bin_dir' later"
    return 0
  fi
  rest="${content#*'{'}"
  case "$content" in
    *'"install_bin_dir"'*)
      before="${content%%'"install_bin_dir"'*}"
      after="${content#*'"install_bin_dir"'}"
      trimmed="${after#"${after%%[![:space:]]*}"}"
      if [ "${trimmed:0:1}" != ":" ]; then
        warn "Could not update $settings; run 'squirrel self install --bin-dir $bin_dir' later"
        return 0
      fi
      trimmed="${trimmed#:}"
      trimmed="${trimmed#"${trimmed%%[![:space:]]*}"}"
      if [ "${trimmed:0:4}" != "null" ]; then
        # A directory is already recorded. It is very likely this one (the
        # installer picks the same directory every time); if not, say so.
        if [ "$bin_dir" != "$HOME/.local/bin" ]; then
          warn "$settings already records an install directory; if it is not $bin_dir, run 'squirrel self install --bin-dir $bin_dir'"
        fi
        return 0
      fi
      content="${before}\"install_bin_dir\": \"${bin_dir}\"${trimmed#null}" ;;
    *)
      body="${rest#"${rest%%[![:space:]]*}"}"
      if [ "${body:0:1}" = "}" ]; then
        # An empty object: no trailing comma.
        content="${lead}{
  \"install_bin_dir\": \"${bin_dir}\"
${rest}"
      else
        content="${lead}{
  \"install_bin_dir\": \"${bin_dir}\",${rest}"
      fi ;;
  esac
  if printf '%s\n' "$content" >"$tmp" 2>/dev/null && chmod 600 "$tmp" 2>/dev/null \
      && mv -f "$tmp" "$settings" 2>/dev/null; then
    return 0
  fi
  rm -f "$tmp" 2>/dev/null
  warn "Could not update $settings; run 'squirrel self install --bin-dir $bin_dir' later"
  return 0
}

# Lay the release out exactly as `self install` would. Prints the installed
# binary path on success. Failure (a mkdir/cp/ln error) returns non-zero with
# the reason on stderr; the caller decides how to report it.
place_release_by_hand() {
  local binary="$1" version="$2" bin_dir="$3"
  local home release_dir target link
  home=$(squirrel_home_dir)
  release_dir="$home/releases/${version#v}"
  target="$release_dir/squirrel"
  link="$bin_dir/squirrel"

  mkdir -p "$release_dir" "$bin_dir" || return 1
  # Copy to a sibling and rename over: a reader never sees a half-written binary.
  cp "$binary" "$target.tmp.$$" && chmod 755 "$target.tmp.$$" && mv -f "$target.tmp.$$" "$target" || {
    rm -f "$target.tmp.$$" 2>/dev/null
    return 1
  }
  # rm acts on the link itself, so a live, dangling or plain-file occupant all
  # go the same way (the existsSync trap from #132 applies to `-e` too).
  rm -f "$link" 2>/dev/null || true
  ln -s "$target" "$link" || return 1
  record_install_bin_dir "$home/settings.json" "$bin_dir"
  printf '%s' "$target"
}

# Indirected so the tests can answer for a Mac from a Linux runner.
is_darwin() {
  [ "$(uname -s 2>/dev/null)" = "Darwin" ]
}

# The macOS release, e.g. 15.6. Empty anywhere else, and on a Mac where the
# command is missing, so every caller has to cope with an empty value.
macos_product_version() {
  sw_vers -productVersion 2>/dev/null || true
}

# What to tell a user whose binary is installed but will not run. Everything
# the user needs is stated as a path or a command: nothing here says "retry".
binary_unrunnable_guidance() {
  local code="$1" target="$2" link="$3" mib="" out="" macos_version=""
  mib=$( (available_memory_mib) 2>/dev/null || true)
  out="  squirrel is installed, but this machine could not run it:
    Binary: ${target}
    Link:   ${link}
  Nothing needs downloading again: once the machine can run it, use it as is.
"
  if [ "$code" = 137 ] && is_darwin; then
    # On macOS a SIGKILL before the process prints anything is a rejection,
    # not the OOM killer: `squirrel --version` does not exhaust a Mac. Either
    # the code signature did not satisfy the kernel or security software
    # refused a binary it has not approved (#2310).
    macos_version=$(macos_product_version)
    out="${out}
  macOS killed it (SIGKILL) before it printed anything, which on a Mac is
  almost always the code signature being rejected, or security software
  (Santa, an MDM policy, an EDR agent) refusing a binary it has not approved."
    if [ -n "$macos_version" ]; then
      out="${out}
  macOS version: ${macos_version}"
    fi
    out="${out}

  Check which of the two it is:
    codesign --verify --strict $(shell_quote "$target")
  A signature error there is the published binary at fault, not this machine:
  install the latest release, which re-signs its darwin binaries, or report it
  at https://github.com/${REPO}/issues
  A valid signature means your security software stopped it: allow
  ${target} in its policy, then run: squirrel --version"
  elif [ "$code" = 137 ]; then
    out="${out}
  The system killed it (SIGKILL), which on a small VPS or a memory-capped
  container is almost always the out-of-memory killer."
    if [ -n "$mib" ]; then
      out="${out}
  Memory available right now: ${mib} MB"
    fi
    out="${out}

  Give the machine more memory, then run: squirrel --version
    Add 1GB of swap (usually the quickest fix on a VPS):
      sudo fallocate -l 1G /swapfile && sudo chmod 600 /swapfile
      sudo mkswap /swapfile && sudo swapon /swapfile
    Or resize the machine, or raise the container memory limit, to 1GB or more."
  elif [ "$code" = 143 ]; then
    out="${out}
  Something outside the installer stopped it (SIGTERM): a timeout wrapper, a
  process supervisor or a cancelled job. Run it again outside that limit:
    squirrel --version"
  else
    out="${out}
  Run it yourself to see the failure:
    ${link} --version"
  fi
  out="${out}

  Cannot change this machine? Audits also run from the cloud dashboard, with
  no binary at all: https://app.squirrelscan.com"
  printf '%s' "$out"
}

# The host of the request in flight, for a report that would otherwise say only
# "curl exit 7" (INSTALLER-WORKER-7: 82 events that could not be told apart). Host
# only: no path, query or credentials, which a report must never carry.
LAST_FETCH_HOST=""
# curl's exit code of the last request that failed with a network code (see is_curl_network_code), so a
# report whose own exit code is the installer's (error() exits 1) can still name the host and family.
LAST_CURL_CODE=""
note_fetch_host() {
  local rest="${1#*://}"
  rest="${rest%%/*}"
  rest="${rest%%\?*}"
  # A fragment ends the authority too: in `https://evil.com#x@install.squirrelscan.com/` the host is
  # evil.com, and reading past the `#` would label it as ours.
  rest="${rest%%#*}"
  rest="${rest##*@}"
  LAST_FETCH_HOST="${rest%%:*}"
  LAST_CURL_CODE=""
  write_fetch_state
}

# The state file holds `host|code`: written from any subshell, read once by the exit trap.
write_fetch_state() {
  [ -n "${FETCH_HOST_FILE:-}" ] && printf '%s|%s' "$LAST_FETCH_HOST" "$LAST_CURL_CODE" >"$FETCH_HOST_FILE" 2>/dev/null || true
}

# Record how the request just made ended, by curl's exit code `$1`: a network failure is remembered (so a
# report can name where it was going), and anything else, success included, forgets an earlier one. The
# LAST request decides: a download that timed out and then succeeded on its retry must not leave a
# failure behind for an unrelated error later in the run to inherit.
note_fetch_rc() {
  if is_curl_network_code "$1"; then
    LAST_CURL_CODE="$1"
  else
    LAST_CURL_CODE=""
  fi
  write_fetch_state
}

# Fill LAST_FETCH_HOST and LAST_CURL_CODE from the file a subshell wrote, where this shell has none.
load_fetch_state() {
  local state=""
  if [ -n "${FETCH_HOST_FILE:-}" ] && [ -f "$FETCH_HOST_FILE" ]; then
    state=$(cat "$FETCH_HOST_FILE" 2>/dev/null)
  fi
  [ -z "$state" ] && return 0
  [ -z "$LAST_FETCH_HOST" ] && LAST_FETCH_HOST="${state%%|*}"
  [ -z "$LAST_CURL_CODE" ] && LAST_CURL_CODE="${state#*|}"
  return 0
}

# A host a report may name: ours, or the GitHub hosts the release assets live on. Anything else (a
# SQUIRREL_RELEASES_ENDPOINT or SQUIRREL_DOWNLOAD_ENDPOINT override, a proxy, an internal mirror) is
# reported as "custom": an installer report never carries a name from the user's own network.
reportable_host() {
  case "$1" in
    install.squirrelscan.com | github.com | api.github.com | objects.githubusercontent.com | release-assets.githubusercontent.com)
      printf '%s' "$1" ;;
    *.githubusercontent.com)
      printf '%s' "$1" ;;
    "") ;;
    *) printf 'custom' ;;
  esac
}

# Which IP family a connection to `host` is attempted on: v4, v6, or unknown (no address was tried:
# the name did not resolve, or the probe could not run). Read from curl's own "Trying <address>" line
# of a verbose request; an IPv4 address with its port has one colon, an IPv6 one has more. Only ever
# run against one of our own hosts, from the detached reporter, never on the install path. It ignores
# proxy settings (--noproxy '*'): behind a proxy the "Trying" line is the proxy's address, which says
# nothing about the family of the connection that failed, so a proxy-only network reads as unknown.
probe_ip_family() {
  local trace addr
  trace=$(curl "${CURL_TLS_ARGS[@]}" -sS -I -o /dev/null -v --noproxy '*' --connect-timeout 3 --max-time 5 \
    "https://${1}/" 2>&1 | grep -m1 'Trying ' || true)
  addr="${trace#*Trying }"
  addr="${addr%%...*}"
  case "$addr" in
    "") printf 'unknown' ;;
    *:*:*) printf 'v6' ;;
    *) printf 'v4' ;;
  esac
}

# curl's own exit codes for "could not reach the server": 6 host not resolved,
# 7 could not connect, 28 timed out, 35 TLS handshake, 52 empty reply, 56 receive
# failure. Under `set -e` the script dies with the code and no message.
is_curl_network_code() {
  case "$1" in 6 | 7 | 28 | 35 | 52 | 56) return 0 ;; *) return 1 ;; esac
}

# Remember the command that failed. Called from the ERR trap with the line and BASH_COMMAND; keeps the first word
# only, stripped of any path and of everything but a plain name, so no argument, path or value is ever kept.
record_failed_command() {
  local name="${2%%[[:space:]]*}"
  name="${name##*/}"
  name="${name//[!A-Za-z0-9_.-]/}"
  FAILED_CMD="${name:0:32}"
  FAILED_LINE="${1//[!0-9]/}"
  return 0
}

# The message for an exit nobody explained: which command failed (when the ERR trap saw it), the exit code, how the
# script was run and the bash version. Fixed vocabulary plus numbers, nothing from the user's machine.
describe_unrecorded_exit() {
  local what="no failing command was recorded"
  if [ -n "$FAILED_CMD" ]; then
    what="'$FAILED_CMD' failed"
    [ -n "$FAILED_LINE" ] && what="$what at line $FAILED_LINE"
  fi
  printf 'exit %s: %s (%s, bash %s.%s)' "$1" "$what" "$INSTALLER_INVOCATION" "${BASH_VERSINFO[0]:-0}" "${BASH_VERSINFO[1]:-0}"
}

# Single EXIT trap: cleans the temp dir and reports genuine failures. Replaces
# the per-call tmpdir trap (a second `trap ... EXIT` would clobber this one).
report_on_exit() {
  local code=$?
  set +e  # cleanup/reporting must never derail the exit path
  # End the download first and wait for it, so it is not writing into the directory removed next.
  if [ -n "$CHILD_PID" ]; then
    kill "$CHILD_PID" 2>/dev/null
    wait "$CHILD_PID" 2>/dev/null
  fi
  [ -n "$TMPDIR_TO_CLEAN" ] && rm -rf "$TMPDIR_TO_CLEAN"
  [ -n "$STAGE_TO_CLEAN" ] && rm -rf "$STAGE_TO_CLEAN"
  # Prefer the in-process message; fall back to the file for subshell failures.
  local msg="$LAST_ERROR_MSG"
  if [ -z "$msg" ] && [ -n "${ERROR_MSG_FILE:-}" ] && [ -f "$ERROR_MSG_FILE" ]; then
    msg=$(cat "$ERROR_MSG_FILE" 2>/dev/null)
  fi
  [ -n "${ERROR_MSG_FILE:-}" ] && rm -f "$ERROR_MSG_FILE"
  # Read the host a subshell wrote, then remove the file on every exit path (a signal returns below).
  load_fetch_state
  [ -n "${FETCH_HOST_FILE:-}" ] && rm -f "$FETCH_HOST_FILE"
  FETCH_HOST_FILE=""
  [ "$code" -eq 0 ] && return 0
  # An interrupt, hangup or terminate is the user (or the system) stopping the run, not an installer failure:
  # no report, or every Ctrl-C during a verify step would read as a broken published binary.
  case "$code" in 129 | 130 | 143) return 0 ;; esac
  # error() always exits 1; prefer the failing sub-command's own code when the
  # call site recorded one (self install, which runs under tee).
  [ -n "$LAST_ERROR_CODE" ] && code="$LAST_ERROR_CODE"
  # A bare failure under `set -e` leaves no message. A curl network failure names the host it was talking to (a
  # hostname only), so the report says where, not just which code. Anything else names the command the ERR trap
  # saw, the line, and the bash that ran it; a curl code is NOT blamed on curl unless a request was made or curl
  # was the failing command, which is how a report from nowhere used to read as a network failure (#5020).
  if [ -z "$msg" ]; then
    if is_curl_network_code "$code" && { [ -n "$LAST_FETCH_HOST" ] || [ "$FAILED_CMD" = "curl" ]; }; then
      msg="curl exit $code reaching $(reportable_host "$LAST_FETCH_HOST")"
      [ "$msg" = "curl exit $code reaching " ] && msg="curl exit $code reaching an unknown host (before the first request)"
    else
      msg=$(describe_unrecorded_exit "$code")
    fi
  fi
  report_error "$CURRENT_STEP" "$code" "$msg" "$LAST_ERROR_OUTPUT"
}
trap report_on_exit EXIT
# -E so the ERR trap also fires inside functions and command substitutions.
set -E
# The trap must leave $? as it found it (older bash does not restore it): `rc=$?` after a failed command is how the
# installer reads an exit code it deliberately survives. The subshell `exit` puts the status back.
trap '_err_rc=$?; record_failed_command "$LINENO" "$BASH_COMMAND"; (exit "$_err_rc")' ERR
# bash skips EXIT traps when it is killed by an untrapped fatal signal, so Ctrl-C during a
# download leaked the temp directory and sent no report. Turning each signal into an exit runs
# report_on_exit: the directory is removed and the failure is reported under the step that was
# running. 128 plus the signal number, as a shell would exit.
trap 'LAST_ERROR_MSG="interrupted (SIGINT)"; exit 130' INT
trap 'LAST_ERROR_MSG="terminated (SIGTERM)"; exit 143' TERM
trap 'LAST_ERROR_MSG="hangup (SIGHUP)"; exit 129' HUP

# --- Banner ---------------------------------------------------------------
# The pixel squirrel + wordmark the CLI prints (apps/cli/src/cli/brand.ts),
# pre-rendered because nothing but bash exists at curl|bash time. Truecolor
# where the terminal says so (COLORTERM), 256 colours otherwise.

# BEGIN GENERATED HEADER (scripts/sync-install-header.ts, from apps/cli/src/cli/brand.ts; do not edit)
BANNER_ART_TRUECOLOR=$'  \033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\n  \033[38;2;139;69;19;48;2;139;69;19m▀\033[0m\033[38;2;139;69;19;48;2;139;69;19m▀\033[0m       \033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\033[38;2;222;184;135m▄\033[0m\n  \033[38;2;139;69;19;48;2;139;69;19m▀\033[0m\033[38;2;139;69;19;48;2;139;69;19m▀\033[0m      \033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\033[38;2;160;82;45;48;2;0;0;0m▀\033[0m     \033[1;38;2;205;133;63msquirrelscan\033[0m\n   \033[38;2;139;69;19;48;2;139;69;19m▀\033[0m\033[38;2;139;69;19;48;2;139;69;19m▀\033[0m \033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\033[38;2;205;133;63;48;2;205;133;63m▀\033[0m\033[38;2;205;133;63;48;2;205;133;63m▀\033[0m\033[38;2;205;133;63;48;2;205;133;63m▀\033[0m\033[38;2;205;133;63;48;2;205;133;63m▀\033[0m\033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\033[38;2;160;82;45;48;2;160;82;45m▀\033[0m   \033[2mThe website QA tool for your coding agent\033[0m\n    \033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\033[38;2;205;133;63;48;2;205;133;63m▀\033[0m\033[38;2;205;133;63;48;2;205;133;63m▀\033[0m\033[38;2;205;133;63;48;2;205;133;63m▀\033[0m\033[38;2;205;133;63;48;2;205;133;63m▀\033[0m\033[38;2;160;82;45;48;2;160;82;45m▀\033[0m\033[38;2;160;82;45;48;2;160;82;45m▀\033[0m  \033[38;2;139;69;19m▄\033[0m\033[38;2;34;139;34;48;2;139;69;19m▀\033[0m\n      \033[38;2;205;133;63;48;2;205;133;63m▀\033[0m\033[38;2;205;133;63;48;2;205;133;63m▀\033[0m\033[38;2;222;184;135;48;2;222;184;135m▀\033[0m\033[38;2;222;184;135;48;2;222;184;135m▀\033[0m\033[38;2;205;133;63;48;2;205;133;63m▀\033[0m\033[38;2;205;133;63;48;2;205;133;63m▀\033[0m  \033[38;2;139;69;19m▀\033[0m\033[38;2;139;69;19m▀\033[0m\n      \033[38;2;139;69;19;48;2;139;69;19m▀\033[0m\033[38;2;139;69;19;48;2;139;69;19m▀\033[0m  \033[38;2;139;69;19;48;2;139;69;19m▀\033[0m\033[38;2;139;69;19;48;2;139;69;19m▀\033[0m'
BANNER_ART_256=$'  \033[38;5;130;48;5;130m▀\033[0m\033[38;5;130;48;5;130m▀\033[0m\n  \033[38;5;94;48;5;94m▀\033[0m\033[38;5;94;48;5;94m▀\033[0m       \033[38;5;130;48;5;130m▀\033[0m\033[38;5;130;48;5;130m▀\033[0m\033[38;5;180m▄\033[0m\n  \033[38;5;94;48;5;94m▀\033[0m\033[38;5;94;48;5;94m▀\033[0m      \033[38;5;130;48;5;130m▀\033[0m\033[38;5;130;48;5;130m▀\033[0m\033[38;5;130;48;5;130m▀\033[0m\033[38;5;130;48;5;16m▀\033[0m     \033[1;38;5;173msquirrelscan\033[0m\n   \033[38;5;94;48;5;94m▀\033[0m\033[38;5;94;48;5;94m▀\033[0m \033[38;5;130;48;5;130m▀\033[0m\033[38;5;130;48;5;130m▀\033[0m\033[38;5;130;48;5;130m▀\033[0m\033[38;5;130;48;5;130m▀\033[0m\033[38;5;173;48;5;173m▀\033[0m\033[38;5;173;48;5;173m▀\033[0m\033[38;5;173;48;5;173m▀\033[0m\033[38;5;173;48;5;173m▀\033[0m\033[38;5;130;48;5;130m▀\033[0m\033[38;5;130;48;5;130m▀\033[0m   \033[2mThe website QA tool for your coding agent\033[0m\n    \033[38;5;130;48;5;130m▀\033[0m\033[38;5;130;48;5;130m▀\033[0m\033[38;5;173;48;5;173m▀\033[0m\033[38;5;173;48;5;173m▀\033[0m\033[38;5;173;48;5;173m▀\033[0m\033[38;5;173;48;5;173m▀\033[0m\033[38;5;130;48;5;130m▀\033[0m\033[38;5;130;48;5;130m▀\033[0m  \033[38;5;94m▄\033[0m\033[38;5;28;48;5;94m▀\033[0m\n      \033[38;5;173;48;5;173m▀\033[0m\033[38;5;173;48;5;173m▀\033[0m\033[38;5;180;48;5;180m▀\033[0m\033[38;5;180;48;5;180m▀\033[0m\033[38;5;173;48;5;173m▀\033[0m\033[38;5;173;48;5;173m▀\033[0m  \033[38;5;94m▀\033[0m\033[38;5;94m▀\033[0m\n      \033[38;5;94;48;5;94m▀\033[0m\033[38;5;94;48;5;94m▀\033[0m  \033[38;5;94;48;5;94m▀\033[0m\033[38;5;94;48;5;94m▀\033[0m'
BANNER_ART_PLAIN='  ██
  ██       ██▄
  ██      ███▀     squirrelscan
   ██ ██████████   The website QA tool for your coding agent
    ████████  ▄█
      ██████  ▀▀
      ██  ██'
BANNER_TEXT_FALLBACK='  squirrelscan
  The website QA tool for your coding agent'
# END GENERATED HEADER

# Half-block glyphs need a UTF-8 locale to render correctly; CI logs and
# dumb terminals often run C/POSIX. Fall back to plain text there.
is_utf8_locale() {
  local charmap=""
  if command -v locale >/dev/null 2>&1; then
    charmap=$(locale charmap 2>/dev/null || true)
  fi
  case "$charmap" in
    *UTF-8*|*utf-8*|*UTF8*|*utf8*) return 0 ;;
  esac
  local loc="${LC_ALL:-${LC_CTYPE:-${LANG:-}}}"
  case "$loc" in
    *UTF-8*|*utf-8*|*UTF8*|*utf8*) return 0 ;;
    *) return 1 ;;
  esac
}

print_banner() {
  echo ""
  if ! is_utf8_locale; then
    printf '%s\n' "$BANNER_TEXT_FALLBACK"
  elif [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then
    case "${COLORTERM:-}" in
      *truecolor*|*24bit*) printf '%s\n' "$BANNER_ART_TRUECOLOR" ;;
      *) printf '%s\n' "$BANNER_ART_256" ;;
    esac
  else
    printf '%s\n' "$BANNER_ART_PLAIN"
  fi
  echo ""
}

# Check for required commands
check_deps() {
  command -v curl >/dev/null 2>&1 || error "curl is required but not installed"

  if ! command -v jq >/dev/null 2>&1; then
    warn "jq not found, using grep fallback (less reliable)"
    USE_JQ=false
  else
    USE_JQ=true
  fi
}

# Compute SHA256 checksum with fallbacks
compute_sha256() {
  local file="$1"
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$file" | cut -d' ' -f1
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$file" | cut -d' ' -f1
  elif command -v openssl >/dev/null 2>&1; then
    openssl dgst -sha256 "$file" | awk '{print $NF}'
  else
    error "No SHA256 tool found (need sha256sum, shasum, or openssl)"
  fi
}

# Keep these installer metadata guards aligned with the validation in
# apps/cli/src/self/paths.ts. Installer versions may carry the tag's `v`.
valid_release_version() {
  local re='^v?(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'
  [[ "$1" =~ $re ]]
}

valid_release_filename() {
  [[ "$1" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]
}

valid_sha256() {
  [[ "$1" =~ ^[0-9a-fA-F]{64}$ ]]
}

# Wait for the background child in CHILD_PID. A plain `wait` can lose a second signal on bash 3.2 (stock
# macOS, what `curl | bash` runs): two different signals a few ms apart left the installer spinning and deaf.
# Polling with `kill -0` keeps every trap deliverable between short sleeps; `wait` then only collects the status.
wait_child() {
  while kill -0 "$CHILD_PID" 2>/dev/null; do sleep 0.2; done
  wait "$CHILD_PID"
}

# Fetch with retry and timeout
fetch_with_retry() {
  local url="$1"
  local output="$2"
  local attempts=3
  local timeout_connect=10
  local timeout_max=120

  note_fetch_host "$url"
  for i in $(seq 1 $attempts); do
    # In the background and waited for, so a SIGINT, SIGTERM or SIGHUP sent to the installer alone is
    # handled at once (bash defers a trap while a foreground command runs); the exit trap then ends curl.
    curl "${CURL_TLS_ARGS[@]}" -fsSL --connect-timeout "$timeout_connect" --max-time "$timeout_max" "$url" -o "$output" 2>/dev/null &
    CHILD_PID=$!
    local rc=0
    wait_child || rc=$?
    CHILD_PID=""
    note_fetch_rc "$rc"
    if [ "$rc" -eq 0 ]; then
      return 0
    fi
    if [ "$i" -lt "$attempts" ]; then
      warn "Download failed, retrying ($i/$attempts)..."
      sleep 2 &
      CHILD_PID=$!
      wait_child || true
      CHILD_PID=""
    fi
  done
  return 1
}

# --- Release asset download (two sources) ---------------------------------
# GitHub is the origin and always has every asset, so it is tried first; the
# mirror at DOWNLOAD_ENDPOINT proxies the same bytes through Cloudflare, which
# reaches GitHub even when the client cannot. The manifest's sha256 is verified
# over whatever comes back either way, so a second source adds no trust.
#
# A mirror that answers 404 is treated as "nothing here", which is also what a
# worker deployed before the route existed answers: the script degrades to the
# GitHub failure it would have reported anyway rather than breaking.
DOWNLOAD_URL_GITHUB=""
DOWNLOAD_URL_MIRROR=""
DOWNLOAD_SOURCE=""

# Opt-in flag semantics, matching the CLI's SQUIRREL_NO_UPDATE: empty, 0 and
# false are off, anything else is on. Presence semantics (as NO_TELEMETRY uses)
# would make a stray `SQUIRREL_FORCE_MIRROR=` in a profile silently reroute
# every install.
force_mirror_enabled() {
  local value
  value=$(printf '%s' "${SQUIRREL_FORCE_MIRROR:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
  case "$value" in
    "" | 0 | false) return 1 ;;
    *) return 0 ;;
  esac
}

# A 200 is not the same as the file we asked for. A captive portal, a proxy
# error page, or a bucket that answers every path with its index all return
# HTML with a 200, and the transport is perfectly happy. Without this the HTML
# reached the manifest parser, jq died on it, and `set -e` took the script down
# with an empty report: exit 5, no message, no URLs, nothing anyone could act
# on. Content that is not a manifest means this SOURCE failed, so the mirror
# still gets its turn.
manifest_looks_valid() {
  local file="$1"
  [ -s "$file" ] || return 1
  # `${USE_JQ:-false}`, not `$USE_JQ`: check_deps sets it, and under `set -u` a
  # bare reference is fatal anywhere this helper is reached first (a test
  # sourcing the script, or a future caller moved above check_deps). Same
  # defensive form json_get already uses.
  if [ "${USE_JQ:-false}" = true ]; then
    jq -e 'type == "object" and has("version") and has("binaries")
           and (.binaries | type == "object")' "$file" > /dev/null 2>&1
    return $?
  fi

  # No jq: the same facts by hand, and the two paths have to agree or a machine
  # without jq gets a different verdict on the same bytes.
  #
  # First non-whitespace byte must be `{`. That is what separates a manifest
  # from a page that merely mentions one: an HTML error page carrying
  # `{"version":...}` inside a <script> tag passes any test that only looks for
  # the keys, and the jq path rejects it, so without this the two disagree.
  local first
  first=$(tr -d '[:space:]' < "$file" 2> /dev/null | cut -c1)
  [ "$first" = "{" ] || return 1

  # Flattened before matching: JSON may put the value on the line after its key,
  # and grep is line-based, so a pretty-printed manifest that happens to wrap
  # after `"binaries":` would otherwise be rejected as invalid. Rejecting a
  # GOOD manifest is the worse failure of the two.
  local flat
  flat=$(tr -d '\n' < "$file" 2> /dev/null)
  case "$flat" in
    *'"version"'*) ;;
    *) return 1 ;;
  esac
  case "$flat" in
    *'"binaries"'*) ;;
    *) return 1 ;;
  esac
  return 0
}

# fetch_release_asset <version> <asset> <output> <label> [validator]
# Leaves both attempted URLs in DOWNLOAD_URL_GITHUB / DOWNLOAD_URL_MIRROR for
# the failure report, and the winner in DOWNLOAD_SOURCE. `validator` is an
# optional function name run on the downloaded file; a source whose bytes do not
# pass it is a failed source, not a successful download of the wrong thing.
fetch_release_asset() {
  local version="$1" asset="$2" output="$3" label="$4" validator="${5:-}"

  valid_release_version "$version" || error "Invalid release version in metadata"
  valid_release_filename "$asset" || error "Invalid release asset filename in metadata"

  DOWNLOAD_URL_GITHUB="https://github.com/${REPO}/releases/download/${version}/${asset}"
  DOWNLOAD_URL_MIRROR="${DOWNLOAD_ENDPOINT}/${version}/${asset}"
  DOWNLOAD_SOURCE=""

  if force_mirror_enabled; then
    info "SQUIRREL_FORCE_MIRROR is set, skipping github.com"
  elif fetch_with_retry "$DOWNLOAD_URL_GITHUB" "$output"; then
    if [ -z "$validator" ] || "$validator" "$output"; then
      DOWNLOAD_SOURCE="github.com"
      return 0
    fi
    warn "github.com returned something that is not a $label, trying install.squirrelscan.com..."
  else
    warn "github.com could not serve the $label, trying install.squirrelscan.com..."
  fi

  if fetch_with_retry "$DOWNLOAD_URL_MIRROR" "$output"; then
    if [ -z "$validator" ] || "$validator" "$output"; then
      DOWNLOAD_SOURCE="install.squirrelscan.com"
      return 0
    fi
    warn "install.squirrelscan.com returned something that is not a $label"
  fi
  return 1
}

# Reduce a URL to scheme, host and path before it is printed or reported.
# SQUIRREL_DOWNLOAD_ENDPOINT is user-supplied and every part of it that can hold
# a secret has to go: it can sit in the userinfo before the host, in the query
# after the path, or in the fragment. The report scrubber strips home paths and
# clamps length; it knows nothing about URL structure, so anything left here
# reaches the reporting endpoint verbatim. Scheme, host and path are all a reader needs to tell which host was
# tried, which is the whole point of carrying the URL at all.
# Order is load-bearing, and getting it wrong leaks. `[^/@]*@` happily crosses a
# `?`, so run against `https://host?token=user@secret/path` the userinfo rule
# ate `host?token=user@` and promoted the token's value to the host: the secret
# survived, in the report and on screen. Cut the query and fragment off first,
# then strip userinfo from what is left, and bound that pattern so it cannot
# cross a delimiter even if the order is ever changed back.
redact_url() {
  printf '%s' "$1" | sed -E -e 's|[?#].*$||' -e 's#^([a-zA-Z][a-zA-Z0-9+.-]*://)[^/?#@]*@#\1#'
}

# Single-quote a value so the recipe we print is copy-pasteable even when the
# path holds a space or a shell metacharacter. A literal quote inside closes the
# string, escapes, and reopens: it's -> 'it'\''s'.
shell_quote() {
  printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
}

# The report line and the user-facing guidance for a download that ran out of
# sources. error() carries the first to Sentry (clamped to ERROR_LINE_MAX, which
# two full URLs would blow past) and prints the second to the user only; the
# URLs themselves ride along in error_output, which has room for them.
#
# The line names the hosts AND the way out, because it is the one line that
# reaches both the user's terminal and the Sentry issue title area — the
# guidance below it is local only.
download_failure_report_line() {
  local label="$1"
  if force_mirror_enabled; then
    echo "Failed to download the $label from install.squirrelscan.com (SQUIRREL_FORCE_MIRROR is set, github.com was skipped)"
  else
    echo "Failed to download the $label from github.com and install.squirrelscan.com (retry with SQUIRREL_FORCE_MIRROR=1 to skip github.com)"
  fi
}

# Skipped is not failed: with SQUIRREL_FORCE_MIRROR set we never asked GitHub,
# and a report claiming we did would send whoever reads it after the wrong host.
download_failure_output() {
  if force_mirror_enabled; then
    printf 'skipped %s (SQUIRREL_FORCE_MIRROR)\ntried %s (failed)\n' \
      "$(redact_url "$DOWNLOAD_URL_GITHUB")" \
      "$(redact_url "$DOWNLOAD_URL_MIRROR")"
  else
    printf 'tried %s (failed)\ntried %s (failed)\n' \
      "$(redact_url "$DOWNLOAD_URL_GITHUB")" \
      "$(redact_url "$DOWNLOAD_URL_MIRROR")"
  fi
}

# download_failure_guidance <asset> <kind> <bin_dir>
# `kind` is `binary` or `manifest`: only the binary has a by-hand recipe worth
# printing, because only the binary is the thing the user ultimately needs on
# disk. Telling someone to move a manifest.json to ~/.local/bin/squirrel would
# be worse than saying nothing. `bin_dir` is the directory this run actually
# resolved, so the recipe names the same place a successful install would use.
download_failure_guidance() {
  local asset="$1" kind="$2" bin_dir="$3" quoted_bin_dir
  quoted_bin_dir=$(shell_quote "$bin_dir")
  echo "  Tried:"
  if force_mirror_enabled; then
    echo "    github.com               skipped (SQUIRREL_FORCE_MIRROR is set)"
  else
    echo "    github.com               $(redact_url "$DOWNLOAD_URL_GITHUB")"
  fi
  echo "    install.squirrelscan.com $(redact_url "$DOWNLOAD_URL_MIRROR")"
  echo ""
  if ! force_mirror_enabled; then
    # The variable has to reach the bash that runs the SCRIPT, not the curl
    # that fetches it, so it goes on the right-hand side of the pipe.
    echo "  If github.com is blocked on this network, skip it and retry:"
    echo "    curl -fsSL https://install.squirrelscan.com | SQUIRREL_FORCE_MIRROR=1 bash"
    echo ""
  fi
  if [ "$kind" = binary ]; then
    echo "  If both hosts are blocked, download $asset on a machine that can"
    echo "  reach one of them, copy it here, then:"
    echo "    chmod +x $asset && mkdir -p $quoted_bin_dir && mv $asset $(shell_quote "$bin_dir/squirrel")"
  else
    echo "  If both hosts are blocked, this machine cannot reach anywhere the"
    echo "  release is published. Allowlist github.com or install.squirrelscan.com,"
    echo "  or install from a network that already reaches one of them."
  fi
}

# Detect platform and architecture
detect_platform() {
  local os arch libc=""

  os=$(uname -s | tr '[:upper:]' '[:lower:]')
  arch=$(uname -m)

  case "$os" in
    darwin) os="darwin" ;;
    linux)
      os="linux"
      libc=$(detect_libc)
      ;;
    freebsd)
      error "FreeBSD is not yet supported. See: https://github.com/${REPO}/issues"
      ;;
    mingw*|msys*|cygwin*)
      error "This installer is for macOS/Linux. On Windows, run this in PowerShell instead:\n  powershell -c \"irm https://install.squirrelscan.com/install.ps1 | iex\"\n  Or download manually from: https://github.com/${REPO}/releases"
      ;;
    *) error "Unsupported OS: $os" ;;
  esac

  case "$arch" in
    x86_64|amd64) arch="x64" ;;
    arm64|aarch64) arch="arm64" ;;
    *) error "Unsupported architecture: $arch" ;;
  esac

  echo "${os}-${arch}${libc}"
}

# Ensure the musl C++ runtime is present.
# bun's musl --compile binary dynamically links libstdc++.so.6 + libgcc_s.so.1,
# which a bare Alpine image lacks — without them the binary can't even run
# `self install`. Auto-install as root via apk; otherwise print the exact
# command and exit cleanly (better than a wall of relocation errors).
ensure_musl_runtime() {
  # Signed releases are checked with openssl; a bare Alpine image lacks it too.
  # Only the C++ runtime is fatal when missing: without openssl the GitHub
  # attestation can still carry the install (see openssl_missing_hint).
  local need_openssl=false have_libstdcxx=false
  command -v openssl >/dev/null 2>&1 || need_openssl=true
  # Already resolvable by the musl loader (/lib or /usr/lib)?
  if ls /usr/lib/libstdc++.so.6 >/dev/null 2>&1 ||
    ls /lib/libstdc++.so.6 >/dev/null 2>&1; then
    have_libstdcxx=true
  fi

  if [ "$have_libstdcxx" = true ] && [ "$need_openssl" = false ]; then
    return 0
  fi

  if command -v apk >/dev/null 2>&1 && [ "$(id -u)" = "0" ]; then
    local pkgs=""
    [ "$have_libstdcxx" = true ] || pkgs="libstdc++"
    [ "$need_openssl" = false ] || pkgs="$pkgs openssl"
    pkgs="${pkgs# }"
    log "Installing required runtime packages ($pkgs)..."
    # shellcheck disable=SC2086 # $pkgs is a space-separated package list
    if apk add --no-cache $pkgs >/dev/null 2>&1; then
      info "Installed $pkgs"
      return 0
    fi
    if [ "$have_libstdcxx" = true ]; then
      # Only openssl was missing: not fatal, the attestation path remains.
      warn "Auto-install of openssl failed"
      return 0
    fi
    # apk add is atomic: a failing openssl also kept libstdc++ out. Retry the
    # required package alone so a mirror without openssl does not fail the install.
    if [ "$need_openssl" = true ] && apk add --no-cache libstdc++ >/dev/null 2>&1; then
      info "Installed libstdc++"
      warn "Auto-install of openssl failed"
      return 0
    fi
    warn "Auto-install of $pkgs failed"
  fi

  # Only openssl is missing and we could not add it: say so, keep going.
  if [ "$have_libstdcxx" = true ]; then
    warn "openssl is not installed; signed releases need it (or a logged-in gh). Fix: apk add openssl"
    return 0
  fi

  # Non-root, no apk, or apk failed → clear, actionable instructions.
  warn "squirrel needs libstdc++ to run on Alpine/musl."
  if command -v apk >/dev/null 2>&1; then
    local fix_pkgs="libstdc++"
    [ "$need_openssl" = false ] || fix_pkgs="libstdc++ openssl"
    echo "  Install it, then re-run the installer:" >&2
    if [ "$(id -u)" = "0" ] || ! command -v sudo >/dev/null 2>&1; then
      echo "      apk add $fix_pkgs" >&2
    else
      echo "      sudo apk add $fix_pkgs" >&2
    fi
  else
    echo "  Install libstdc++ (and libgcc) with your package manager, then re-run." >&2
  fi
  echo "  More: https://docs.squirrelscan.com/install (Alpine / musl Linux note)" >&2
  error "Missing libstdc++ (required by the musl build)"
}

# True when $1 is an entry of the current PATH.
dir_in_path() {
  local target="${1%/}" entry
  local entries
  IFS=':' read -ra entries <<< "$PATH"
  for entry in "${entries[@]}"; do
    [ "${entry%/}" = "$target" ] && return 0
  done
  return 1
}

# Find a writable bin directory that's in PATH
find_bin_dir() {
  # If user explicitly set bin dir, use it
  if [ -n "${SQUIRREL_BIN_DIR:-}" ]; then
    mkdir -p "$SQUIRREL_BIN_DIR" 2>/dev/null || true
    if [ -d "$SQUIRREL_BIN_DIR" ] && [ -w "$SQUIRREL_BIN_DIR" ]; then
      echo "$SQUIRREL_BIN_DIR"
      return 0
    else
      warn "SQUIRREL_BIN_DIR=$SQUIRREL_BIN_DIR is not writable, searching PATH..."
    fi
  fi

  # Priority order of common bin directories
  local common_dirs=(
    "$HOME/.local/bin"      # XDG standard
    "$HOME/bin"             # Traditional user bin
    "/usr/local/bin"        # System-wide
    "/opt/homebrew/bin"     # macOS ARM Homebrew
  )

  # Parse PATH into array
  local path_dirs
  IFS=':' read -ra path_dirs <<< "$PATH"

  # First: check if any common dir is already in PATH and writable
  for dir in "${common_dirs[@]}"; do
    for path_dir in "${path_dirs[@]}"; do
      if [ "$dir" = "$path_dir" ]; then
        if [ -d "$dir" ] && [ -w "$dir" ]; then
          echo "$dir"
          return 0
        elif [ ! -e "$dir" ]; then
          # Directory doesn't exist but parent might be writable
          local parent
          parent=$(dirname "$dir")
          if [ -w "$parent" ]; then
            mkdir -p "$dir" 2>/dev/null && echo "$dir" && return 0
          fi
        fi
      fi
    done
  done

  # Fallback: create ~/.local/bin (will need PATH modification)
  mkdir -p "$HOME/.local/bin" 2>/dev/null
  echo "$HOME/.local/bin"
  return 1  # Signal that PATH update needed
}

# JSON value extraction with grep fallback
json_get() {
  local json="$1" key="$2"
  echo "$json" | grep -o "\"$key\"[[:space:]]*:[[:space:]]*\"[^\"]*\"" | \
    sed 's/.*:[[:space:]]*"\([^"]*\)".*/\1/' | head -1
}

# JSON nested value extraction (for binaries["platform"])
json_get_nested() {
  local json="$1" outer="$2" inner="$3"
  # Extract the outer block first, then the inner value
  local block
  block=$(echo "$json" | tr '\n' ' ' | grep -o "\"$outer\"[[:space:]]*:[[:space:]]*{[^}]*}" | head -1)
  echo "$block" | grep -o "\"$inner\"[[:space:]]*:[[:space:]]*\"[^\"]*\"" | \
    sed 's/.*:[[:space:]]*"\([^"]*\)".*/\1/' | head -1
}

# A whole-number value in the `outer` block (the manifest's `size`), or nothing.
json_get_nested_number() {
  local json="$1" outer="$2" inner="$3"
  local block
  block=$(echo "$json" | tr '\n' ' ' | grep -o "\"$outer\"[[:space:]]*:[[:space:]]*{[^}]*}" | head -1)
  echo "$block" | grep -o "\"$inner\"[[:space:]]*:[[:space:]]*[0-9][0-9]*" | \
    sed 's/.*:[[:space:]]*\([0-9][0-9]*\)$/\1/' | head -1
}

# Get latest release version.
# Primary: install.squirrelscan.com/releases/{channel} — R2-backed release
# metadata with no rate limits. Fallback: the GitHub API, which anonymous
# clients share at 60 req/hr per IP — corporate NAT/VPN/CI egress hits 403s.
# Split a `curl -w $'\n@@status:%{http_code}'` capture into RESP_BODY and RESP_STATUS. A capture
# without the marker (a curl that ignored -w, a killed request) leaves the status empty.
split_status_marker() {
  local raw="$1"
  RESP_STATUS=""
  RESP_BODY="$raw"
  case "$raw" in
    *$'\n@@status:'*)
      RESP_STATUS="${raw##*$'\n@@status:'}"
      RESP_BODY="${raw%$'\n@@status:'*}"
      ;;
  esac
  # Only three digits are ever reported, never whatever a server put after the marker.
  case "$RESP_STATUS" in [0-9][0-9][0-9]) ;; *) RESP_STATUS="" ;; esac
}

# describe_fetch_outcome <label> <curl rc> <http status>
# One short, fixed-vocabulary phrase per endpoint (host label, curl exit code, HTTP status): no URL,
# path, response body or user text, so it is safe in error_line and inside the report allowlist.
# A zero rc means the endpoint answered but the answer held no release data.
describe_fetch_outcome() {
  local label="$1" rc="$2" status="$3"
  if [ "$rc" -eq 0 ]; then
    printf '%s: HTTP %s but no usable release data' "$label" "${status:-200}"
  elif [ -n "$status" ] && [ "$status" != "000" ]; then
    printf "%s: HTTP %s (curl exit %s)" "$label" "$status" "$rc"
  else
    printf "%s: curl exit %s" "$label" "$rc"
  fi
}

# fetch_failure_message <primary outcome> <fallback outcome> <network: yes|no>
fetch_failure_message() {
  if [ "$3" = yes ]; then
    printf 'Cannot reach the release servers (%s; %s)' "$1" "$2"
  else
    printf 'The release endpoints returned something unusable (%s; %s)' "$1" "$2"
  fi
}

# Remediation text for the user (not carried in the report): the manual download URL and a pin.
fetch_failure_guidance() {
  if [ "$1" = yes ]; then
    echo "  This machine could not connect. Check your network, proxy or firewall settings."
  else
    echo "  A release endpoint answered, but not with release data. Retrying later usually helps."
  fi
  echo "  Download a release by hand: https://github.com/${REPO}/releases"
  echo "  Or pin a version once you know it: curl -fsSL https://install.squirrelscan.com | SQUIRREL_VERSION=<version> bash"
}

get_latest_version() {
  local channel="${1:-stable}"
  local api_url="https://api.github.com/repos/${REPO}/releases"
  local response version="" primary_label primary_outcome fallback_outcome primary_network=no network=no

  info "Fetching releases (channel: $channel)..."

  note_fetch_host "${RELEASES_ENDPOINT}/${channel}"
  primary_label=$(reportable_host "$LAST_FETCH_HOST")
  [ -z "$primary_label" ] && primary_label="release endpoint"
  local fetch_rc=0
  response=$(curl "${CURL_TLS_ARGS[@]}" -fsSL -H "User-Agent: squirrelscan-installer" \
      --connect-timeout 5 --max-time 15 -w $'\n@@status:%{http_code}' \
      "${RELEASES_ENDPOINT}/${channel}" 2>/dev/null) || fetch_rc=$?
  note_fetch_rc "$fetch_rc"
  split_status_marker "$response"
  response="$RESP_BODY"
  if [ "$fetch_rc" -eq 0 ]; then
    if [ "$USE_JQ" = true ]; then
      version=$(echo "$response" | jq -r '.version // empty' 2>/dev/null || true)
    else
      version=$(json_get "$response" "version" || true)
    fi
    if [ -n "$version" ]; then
      # Manifest versions are bare ("0.0.73"); release tags carry the v prefix.
      echo "v${version#v}"
      return 0
    fi
  fi
  primary_outcome=$(describe_fetch_outcome "$primary_label" "$fetch_rc" "$RESP_STATUS")
  is_curl_network_code "$fetch_rc" && primary_network=yes
  warn "Release metadata endpoint unavailable ($primary_outcome), falling back to GitHub API..."

  # Build curl args - add auth header if GITHUB_TOKEN is set (avoids rate limits)
  local curl_args=("${CURL_TLS_ARGS[@]}" -fsSL -H "User-Agent: squirrelscan-installer" --connect-timeout 10 --max-time 30)
  if [ -n "${GITHUB_TOKEN:-}" ]; then
    curl_args+=(-H "Authorization: token $GITHUB_TOKEN")
  fi
  curl_args+=(-w $'\n@@status:%{http_code}')

  note_fetch_host "$api_url"
  fetch_rc=0
  # stderr is dropped: it can carry the request URL or proxy details, and the outcome is described above.
  response=$(curl "${curl_args[@]}" "$api_url" 2>/dev/null) || fetch_rc=$?
  note_fetch_rc "$fetch_rc"
  split_status_marker "$response"
  response="$RESP_BODY"
  if [ "$fetch_rc" -ne 0 ]; then
    fallback_outcome=$(describe_fetch_outcome "api.github.com" "$fetch_rc" "$RESP_STATUS")
    # Unreachable only when neither endpoint answered at all.
    is_curl_network_code "$fetch_rc" && [ "$primary_network" = yes ] && network=yes
    error "$(fetch_failure_message "$primary_outcome" "$fallback_outcome" "$network")" \
      "$(fetch_failure_guidance "$network")"
  fi

  if [ -z "$response" ] || [ "$response" = "[]" ]; then
    fallback_outcome=$(describe_fetch_outcome "api.github.com" 0 "$RESP_STATUS")
    error "$(fetch_failure_message "$primary_outcome" "$fallback_outcome" no)" \
      "$(fetch_failure_guidance no)"
  fi

  version=""
  if [ "$USE_JQ" = true ]; then
    if [ "$channel" = "stable" ]; then
      version=$(echo "$response" | jq -r '[.[] | select(.prerelease == false)] | .[0].tag_name // empty' 2>/dev/null || true)
    else
      version=$(echo "$response" | jq -r '.[0].tag_name // empty' 2>/dev/null || true)
    fi
  else
    # Grep fallback - just get first tag (works for beta, imprecise for stable)
    version=$(echo "$response" | grep -o '"tag_name": *"[^"]*"' | head -1 | cut -d'"' -f4 || true)
  fi

  # A 200 whose body holds no release at all (a captive-portal or proxy page) is not "no stable
  # releases": report both endpoints' outcomes here, or the caller's message names neither. A real
  # release list that only lacks a stable release still returns empty for the caller to explain.
  # A pattern match, not `printf | grep -q`: under pipefail grep's early exit SIGPIPEs printf on a
  # large list (exit 141), which would call a real release list unusable.
  if [ -z "$version" ]; then
    case "$response" in
      *'"tag_name"'*) ;;
      *)
        fallback_outcome=$(describe_fetch_outcome "api.github.com" 0 "$RESP_STATUS")
        error "$(fetch_failure_message "$primary_outcome" "$fallback_outcome" no)" \
          "$(fetch_failure_guidance no)"
        ;;
    esac
  fi

  echo "$version"
}

# Whether a run of `binary` that exited `rc` failed because the system would not execute it: exit 126
# and the file is not executable to us. `test -x` asks the kernel (access(2)), which refuses on a
# noexec mount whatever the file mode says, so this does not depend on the language of any message.
exec_blocked() {
  [ "$1" -eq 126 ] && [ ! -x "$2" ]
}

# Run `<binary> self install --bin-dir <dir>` under tee into <log>, so the user sees the output live
# and a failure can report what the binary said (#1538). Returns the binary's own exit code, not
# tee's (PIPESTATUS[0]). The caller has `set +e` around it.
run_self_install() {
  local binary="$1" bin_dir="$2" log="$3"
  # Stamp the install channel for the CLI's one-time install registration
  # (self/install-meta.ts honors SQUIRREL_INSTALL_SOURCE; without it the
  # managed-dir binary self-reports as the ambiguous "binary"). A caller's own
  # value wins so wrappers (CI, package managers) can name themselves.
  SQUIRREL_INSTALL_SOURCE="${SQUIRREL_INSTALL_SOURCE:-install-sh}" \
    SQUIRREL_PATH_SETUP="$PATH_SETUP" \
    "$binary" self install --bin-dir "$bin_dir" 2>&1 | tee "$log"
  return "${PIPESTATUS[0]}"
}

# gh_bounded <seconds> <outfile> <gh args...>
# Runs gh with a deadline so a hung gh cannot hang the install. Output goes to
# <outfile>. Returns gh's exit code, or 124 when the deadline hit. Uses
# timeout/gtimeout when present; macOS has neither, so otherwise a background
# process plus a kill watchdog. SQUIRREL_TEST_GH_TIMEOUT_SECS replaces every
# deadline and exists only as a test seam.
gh_bounded() {
  local secs="${SQUIRREL_TEST_GH_TIMEOUT_SECS:-$1}" out="$2"
  shift 2
  local tbin="" rc=0
  if command -v timeout > /dev/null 2>&1; then
    tbin=timeout
  elif command -v gtimeout > /dev/null 2>&1; then
    tbin=gtimeout
  fi
  if [ -n "$tbin" ]; then
    GH_NO_UPDATE_NOTIFIER=1 GH_PROMPT_DISABLED=1 "$tbin" -s KILL "$secs" gh "$@" > "$out" 2>&1 < /dev/null || rc=$?
    # GNU reports 124; some builds report the KILL as 137.
    if [ "$rc" -eq 137 ]; then rc=124; fi
    return "$rc"
  fi
  local flag="${out}.timedout" pid wd
  rm -f "$flag"
  GH_NO_UPDATE_NOTIFIER=1 GH_PROMPT_DISABLED=1 gh "$@" > "$out" 2>&1 < /dev/null &
  pid=$!
  (
    i=0
    while [ "$i" -lt "$secs" ] && kill -0 "$pid" 2> /dev/null; do
      sleep 1
      i=$((i + 1))
    done
    if kill -0 "$pid" 2> /dev/null; then
      : > "$flag"
      kill -9 "$pid" 2> /dev/null
    fi
  ) > /dev/null 2>&1 &
  wd=$!
  wait "$pid" 2> /dev/null || rc=$?
  kill "$wd" 2> /dev/null || true
  wait "$wd" 2> /dev/null || true
  if [ -e "$flag" ]; then
    rm -f "$flag"
    return 124
  fi
  return "$rc"
}

# Signed era (squirrelscan/repo#5032). From RELEASE_FIRST_SIGNED_VERSION up, the
# release is accepted ONLY on a valid pinned-key signature or a valid GitHub
# attestation: sha256 alone is a hard failure, with or without gh. The era is
# decided from the version being installed (the resolved target, whether it came
# from the channel or SQUIRREL_VERSION), never from a manifest field, because
# whoever can strip a .sig can strip a field too. Unset means no era.
# (valid_release_version, above, is the shared version pattern.)
SIGNED_ERA=false
SIGNED_ERA_VERSION=""
SIG_NOTE=""
OPENSSL_MISSING=false

# num_cmp A B: prints -1, 0 or 1 for two digit strings, no arithmetic (no overflow).
num_cmp() {
  local a="$1" b="$2"
  a="${a#"${a%%[!0]*}"}"
  b="${b#"${b%%[!0]*}"}"
  if [ "${#a}" -ne "${#b}" ]; then
    if [ "${#a}" -lt "${#b}" ]; then echo -1; else echo 1; fi
  elif [ "$a" = "$b" ]; then
    echo 0
  elif [[ "$a" < "$b" ]]; then
    echo -1
  else
    echo 1
  fi
}

# version_cmp A B: semver precedence, prints -1, 0 or 1. A leading v and +build
# are ignored, a prerelease sorts below its release, and prerelease identifiers
# compare left to right (numeric below alphanumeric, a shorter list below a
# longer one). Both versions must satisfy valid_release_version. Bash 3.2
# safe: no sort -V, no associative arrays.
version_cmp() {
  local a="${1#v}" b="${2#v}" i c x y xn yn
  a="${a%%+*}"
  b="${b%%+*}"
  local acore="${a%%-*}" bcore="${b%%-*}" apre="" bpre=""
  [ "$a" = "$acore" ] || apre="${a#*-}"
  [ "$b" = "$bcore" ] || bpre="${b#*-}"
  local IFS=.
  local ac bc ap bp
  # shellcheck disable=SC2206
  ac=($acore) bc=($bcore)
  i=0
  while [ "$i" -lt 3 ]; do
    c=$(num_cmp "${ac[$i]}" "${bc[$i]}")
    if [ "$c" != 0 ]; then echo "$c"; return 0; fi
    i=$((i + 1))
  done
  if [ -z "$apre" ] && [ -z "$bpre" ]; then echo 0; return 0; fi
  if [ -z "$apre" ]; then echo 1; return 0; fi
  if [ -z "$bpre" ]; then echo -1; return 0; fi
  # shellcheck disable=SC2206
  ap=($apre) bp=($bpre)
  i=0
  while :; do
    if [ "$i" -ge "${#ap[@]}" ] && [ "$i" -ge "${#bp[@]}" ]; then echo 0; return 0; fi
    if [ "$i" -ge "${#ap[@]}" ]; then echo -1; return 0; fi
    if [ "$i" -ge "${#bp[@]}" ]; then echo 1; return 0; fi
    x="${ap[$i]}"
    y="${bp[$i]}"
    xn=false
    yn=false
    case "$x" in *[!0-9]*) ;; *) xn=true ;; esac
    case "$y" in *[!0-9]*) ;; *) yn=true ;; esac
    if [ "$xn" = true ] && [ "$yn" = true ]; then
      c=$(num_cmp "$x" "$y")
      if [ "$c" != 0 ]; then echo "$c"; return 0; fi
    elif [ "$xn" = true ]; then
      echo -1; return 0
    elif [ "$yn" = true ]; then
      echo 1; return 0
    elif [ "$x" != "$y" ]; then
      local LC_ALL=C
      if [[ "$x" < "$y" ]]; then echo -1; else echo 1; fi
      return 0
    fi
    i=$((i + 1))
  done
}

# release_signed_era <version>: 0 when the version is at or after
# RELEASE_FIRST_SIGNED_VERSION. A version that does not parse counts as
# signed-era, so a malformed target is never the way out of the rule.
release_signed_era() {
  [ -n "${RELEASE_FIRST_SIGNED_VERSION:-}" ] || return 1
  valid_release_version "$1" || return 0
  [ "$(version_cmp "$1" "$RELEASE_FIRST_SIGNED_VERSION")" != "-1" ]
}

# os_release_ids: the lowercase ID and ID_LIKE words of the os-release file
# (OS_RELEASE_FILE overrides /etc/os-release for tests), empty when unreadable.
os_release_ids() {
  local f="${OS_RELEASE_FILE:-/etc/os-release}" line
  [ -r "$f" ] || return 0
  while IFS= read -r line; do
    case "$line" in
      ID=* | ID_LIKE=*)
        line="${line#*=}"
        line="${line//\"/}"
        line="${line//\'/}"
        printf '%s ' "$line"
        ;;
    esac
  done < "$f" | tr '[:upper:]' '[:lower:]'
}

# openssl_missing_hint: the exact fix for a signed release when openssl is
# missing, the line for this distro first, all three when unsure. Never run.
openssl_missing_hint() {
  local ids line_apt line_dnf line_apk first=""
  ids=" $(os_release_ids)"
  line_apt="Debian/Ubuntu: apt-get install -y openssl"
  line_dnf="Fedora/RHEL:   dnf install openssl"
  line_apk="Alpine:        apk add openssl"
  case "$ids" in
    *" debian "* | *" ubuntu "*) first="apt" ;;
    *" fedora "* | *" rhel "* | *" centos "*) first="dnf" ;;
    *" alpine "*) first="apk" ;;
  esac
  printf '  Install openssl (as root, or with sudo), then run the installer again:\n'
  case "$first" in
    apt) printf '    %s\n    %s\n    %s\n' "$line_apt" "$line_dnf" "$line_apk" ;;
    dnf) printf '    %s\n    %s\n    %s\n' "$line_dnf" "$line_apt" "$line_apk" ;;
    apk) printf '    %s\n    %s\n    %s\n' "$line_apk" "$line_apt" "$line_dnf" ;;
    *) printf '    %s\n    %s\n    %s\n' "$line_apt" "$line_dnf" "$line_apk" ;;
  esac
  printf '  or install and log in to the GitHub CLI (gh) so the release attestation can be checked.\n'
}

signed_era_fail() {
  local hint=""
  if [ "$OPENSSL_MISSING" = true ]; then
    hint="\n$(openssl_missing_hint)"
  fi
  error "Cannot verify squirrel ${SIGNED_ERA_VERSION#v}: $1.\n  This version is only installed with a valid release-key signature or GitHub attestation; the sha256 checksum alone is not accepted.\n  Nothing was installed.\n  To install by hand, download the binary and its .sig and check them with openssl dgst -sha256 -verify:\n    https://docs.squirrelscan.com/install#verifying-a-release${hint}"
}

# attestation_skipped <short reason> <warning text>: gh cannot check the
# attestation. Before the signed era that is a warning and the sha256 decides;
# in it, it is a hard failure.
attestation_skipped() {
  if [ "$SIGNED_ERA" = true ]; then
    signed_era_fail "${SIG_NOTE:-no signature was checked}, and the GitHub attestation could not be checked ($1)"
  fi
  warn "$2"
}

# Provenance check (#169). The sha256 above comes from a manifest served next
# to the binary, so it cannot tell a compromised origin from a good one. GitHub
# artifact attestations are signed in the release workflow and checked against
# Sigstore and GitHub, a trust root that is not our download origin.
#   gh usable, attestation matches   -> continue
#   gh usable, attestation mismatch  -> hard failure, nothing is installed
#   gh absent, too old, or logged out -> visible warning, sha256 alone decides
# `gh attestation verify` needs an authenticated gh; a gh that is installed but
# not logged in cannot verify anything, so it counts as absent, never as a pass.
verify_attestation() {
  local file="$1" out rc
  CURRENT_STEP="verify_attestation"
  if ! command -v gh > /dev/null 2>&1; then
    attestation_skipped "gh is not installed" "GitHub CLI (gh) not found: skipping the release provenance check, relying on the sha256 checksum only.\n  Install gh and run 'gh auth login' to verify installs against the GitHub attestation."
    return 0
  fi
  out=$(mktemp)
  rc=0
  gh_bounded 15 "$out" attestation verify --help || rc=$?
  if [ "$rc" -eq 124 ]; then
    rm -f "$out"
    attestation_skipped "gh attestation verify --help timed out" "gh attestation verify --help timed out after ${SQUIRREL_TEST_GH_TIMEOUT_SECS:-15}s: skipping the release provenance check, relying on the sha256 checksum only."
    return 0
  elif [ "$rc" -ne 0 ]; then
    rm -f "$out"
    attestation_skipped "this gh is too old for 'gh attestation verify'" "This gh is too old for 'gh attestation verify': skipping the release provenance check, relying on the sha256 checksum only."
    return 0
  fi
  rc=0
  gh_bounded 15 "$out" auth status --hostname github.com || rc=$?
  if [ "$rc" -eq 124 ]; then
    rm -f "$out"
    attestation_skipped "gh auth status timed out" "gh auth status timed out after ${SQUIRREL_TEST_GH_TIMEOUT_SECS:-15}s: skipping the release provenance check, relying on the sha256 checksum only."
    return 0
  elif [ "$rc" -ne 0 ]; then
    rm -f "$out"
    attestation_skipped "gh is not logged in" "gh is not logged in: skipping the release provenance check, relying on the sha256 checksum only.\n  Run 'gh auth login' to enable it."
    return 0
  fi
  log "Verifying release attestation..."
  rc=0
  gh_bounded 120 "$out" attestation verify "$file" --repo "$REPO" --cert-identity "$CERT_IDENTITY" --deny-self-hosted-runners || rc=$?
  local attest_out
  attest_out=$(cat "$out" 2> /dev/null || true)
  rm -f "$out"
  if [ "$rc" -eq 124 ]; then
    LAST_ERROR_OUTPUT=$(printf '%s\n' "$attest_out" | tail -n 20)
    error "gh attestation verify timed out after ${SQUIRREL_TEST_GH_TIMEOUT_SECS:-120}s, nothing was installed."
  elif [ "$rc" -ne 0 ]; then
    LAST_ERROR_OUTPUT=$(printf '%s\n' "$attest_out" | tail -n 20)
    # printf, not error's detail: that goes through echo -e, which would
    # interpret backslashes in text this script did not write.
    printf '%s\n' "$attest_out" | tail -n 10 >&2
    local no_sig=""
    if release_keys_pinned; then no_sig="\n  The release carries no squirrelscan release-key signature either."; fi
    error "Attestation verification failed: this binary was not built by the ${REPO} release workflow.${no_sig}\n  Nothing was installed. Do not run it."
  fi
  info "Attestation verified: built by ${REPO}"
}

# --- Release-key signature (squirrelscan/repo#5032) -----------------------
# Releases built outside GitHub Actions carry no GitHub attestation. They are
# signed instead: `<asset>.sig` and `manifest.json.sig` are DER ECDSA P-256
# signatures over SHA-256 of the file (`openssl dgst -sha256 -sign`), and the
# manifest names the key in `signing_key_id`. The keys are pinned above.

release_keys_pinned() {
  [ -n "${RELEASE_KEY_CURRENT_PEM:-}" ] || [ -n "${RELEASE_KEY_NEXT_PEM:-}" ]
}

# Prints the PEM of the pinned slot with this id; fails when none pins it.
release_key_pem() {
  local id="$1"
  if [ -n "${RELEASE_KEY_CURRENT_PEM:-}" ] && [ "$id" = "${RELEASE_KEY_CURRENT_ID:-}" ]; then
    printf '%s\n' "$RELEASE_KEY_CURRENT_PEM"
    return 0
  fi
  if [ -n "${RELEASE_KEY_NEXT_PEM:-}" ] && [ "$id" = "${RELEASE_KEY_NEXT_ID:-}" ]; then
    printf '%s\n' "$RELEASE_KEY_NEXT_PEM"
    return 0
  fi
  return 1
}

release_key_revoked() {
  case " ${RELEASE_KEYS_REVOKED:-} " in
    *" $1 "*) return 0 ;;
  esac
  return 1
}

# The URL fetch_release_asset last downloaded from, so a .sig comes from the
# same place as the file it signs.
downloaded_url() {
  if [ "$DOWNLOAD_SOURCE" = "github.com" ]; then
    echo "$DOWNLOAD_URL_GITHUB"
  else
    echo "$DOWNLOAD_URL_MIRROR"
  fi
}

# fetch_signature <url> <output>: one quiet fetch (curl retries transient
# errors itself). An absent .sig is normal for an attested release, so a 404
# warns nothing and costs no retry loop. Signatures are tiny: over 1 KiB is junk.
fetch_signature() {
  local url="$1" output="$2" rc=0 bytes
  rm -f "$output"
  curl "${CURL_TLS_ARGS[@]}" -fsSL --connect-timeout 10 --max-time 30 --retry 2 --retry-delay 1 "$url" -o "$output" 2> /dev/null &
  CHILD_PID=$!
  wait_child || rc=$?
  CHILD_PID=""
  [ "$rc" -eq 0 ] && [ -s "$output" ] || return 1
  bytes=$(wc -c < "$output" | tr -d '[:space:]')
  [ "$bytes" -le 1024 ]
}

signature_failed() {
  error "Release signature verification failed: $1.\n  Nothing was installed. Do not run it."
}

# verify_release_signature <manifest> <binary> <filename> <version> <manifest_url> <binary_url>
# Runs after the sha256 check, which compared the binary to this same manifest
# file. Returns 0 when a pinned key signed both, 1 when the release carries no
# signature (or the check cannot run), so the attestation decides. Anything
# else is a hard failure, even if an attestation would pass:
#   a signature from an unpinned or revoked key, a signature that does not
#   verify, a signed manifest for another version, or one of the two .sig
#   files without the other.
verify_release_signature() {
  local manifest_file="$1" binary="$2" filename="$3" version="$4" manifest_url="$5" binary_url="$6"
  CURRENT_STEP="verify_signature"
  if ! release_keys_pinned; then
    SIG_NOTE="no release key is pinned"
    return 1
  fi
  if ! command -v openssl > /dev/null 2>&1; then
    warn "openssl not found: skipping the release-key signature check, falling back to the GitHub attestation."
    SIG_NOTE="openssl is not installed, so no release-key signature was checked"
    OPENSSL_MISSING=true
    return 1
  fi

  local dir have_manifest_sig=false have_binary_sig=false
  dir=$(dirname "$manifest_file")
  fetch_signature "${manifest_url}.sig" "$dir/manifest.json.sig" && have_manifest_sig=true
  fetch_signature "${binary_url}.sig" "$dir/binary.sig" && have_binary_sig=true
  if [ "$have_manifest_sig" = false ] && [ "$have_binary_sig" = false ]; then
    SIG_NOTE="the release has no .sig files"
    return 1
  fi
  [ "$have_manifest_sig" = true ] || signature_failed "manifest.json.sig is missing"
  [ "$have_binary_sig" = true ] || signature_failed "${filename}.sig is missing"

  local manifest key_id signed_version
  manifest=$(cat "$manifest_file")
  if [ "${USE_JQ:-false}" = true ]; then
    key_id=$(printf '%s' "$manifest" | jq -r '.signing_key_id // empty' 2> /dev/null || true)
    signed_version=$(printf '%s' "$manifest" | jq -r '.version // empty' 2> /dev/null || true)
  else
    key_id=$(json_get "$manifest" "signing_key_id" || true)
    signed_version=$(json_get "$manifest" "version" || true)
  fi
  [[ "$key_id" =~ ^[0-9a-f]{16}$ ]] || signature_failed "manifest.json names no signing key id"
  if release_key_revoked "$key_id"; then
    signature_failed "it is signed with revoked key ${key_id}"
  fi
  local pem_file="$dir/release-key.pem"
  release_key_pem "$key_id" > "$pem_file" ||
    signature_failed "it is signed with key ${key_id}, which this installer does not pin"

  log "Verifying release signature..."
  openssl dgst -sha256 -verify "$pem_file" -signature "$dir/manifest.json.sig" "$manifest_file" > /dev/null 2>&1 ||
    signature_failed "manifest.json is not signed by key ${key_id}"
  # A signed manifest replayed under another version's URL is a downgrade.
  if [ "${signed_version#v}" != "${version#v}" ]; then
    signature_failed "the signed manifest is for version '${signed_version}', not ${version}"
  fi
  openssl dgst -sha256 -verify "$pem_file" -signature "$dir/binary.sig" "$binary" > /dev/null 2>&1 ||
    signature_failed "${filename} is not signed by key ${key_id}"
  info "Release signature verified: signed by squirrelscan release key ${key_id}"
  return 0
}

# Download binary and run self install
download_and_install() {
  local version="$1"
  local platform="$2"
  local bin_dir="$3"
  local tmpdir

  tmpdir=$(mktemp -d)
  # Cleaned by the EXIT trap (report_on_exit) — do NOT set a local EXIT trap
  # here or it clobbers the failure-reporting trap.
  TMPDIR_TO_CLEAN="$tmpdir"

  # Download manifest to get binary filename and checksum
  CURRENT_STEP="download_manifest"
  log "Downloading manifest..."
  if ! fetch_release_asset "$version" "manifest.json" "$tmpdir/manifest.json" "manifest" manifest_looks_valid; then
    LAST_ERROR_OUTPUT=$(download_failure_output)
    error "$(download_failure_report_line manifest)" "$(download_failure_guidance manifest.json manifest "$bin_dir")"
  fi
  local manifest_url
  manifest_url=$(downloaded_url)

  # Read manifest content
  local manifest
  manifest=$(cat "$tmpdir/manifest.json")

  # Extract binary info
  # `|| true` on both: a command substitution carries its command's exit status
  # to the assignment, so a jq that chokes would take the whole script down
  # under `set -e` before the empty-value check below could say anything useful.
  # manifest_looks_valid already rejected a non-manifest, so this is the
  # belt-and-braces half of the same fix.
  local filename sha256 size=""
  if [ "$USE_JQ" = true ]; then
    filename=$(echo "$manifest" | jq -r ".binaries[\"${platform}\"].filename // empty" 2> /dev/null || true)
    sha256=$(echo "$manifest" | jq -r ".binaries[\"${platform}\"].sha256 // empty" 2> /dev/null || true)
    size=$(echo "$manifest" | jq -r ".binaries[\"${platform}\"].size // empty" 2> /dev/null || true)
  else
    # `|| true` for the same reason as the jq branch above: json_get_nested ends
    # in a pipeline, and under `pipefail` a grep that matches nothing makes the
    # whole substitution non-zero, which `set -e` turns into a silent death
    # before the empty-value check below can say anything useful.
    filename=$(json_get_nested "$manifest" "$platform" "filename" || true)
    sha256=$(json_get_nested "$manifest" "$platform" "sha256" || true)
    size=$(json_get_nested_number "$manifest" "$platform" "size" || true)
  fi

  if [ -z "$filename" ] || [ -z "$sha256" ]; then
    error "No binary for platform: $platform\n  See: https://github.com/${REPO}/releases/tag/${version}"
  fi
  valid_release_filename "$filename" || error "Invalid release asset filename in metadata"
  valid_sha256 "$sha256" || error "Invalid SHA256 in release manifest"

  # Download binary
  CURRENT_STEP="download_binary"
  log "Downloading squirrel ${version}..."
  if ! fetch_release_asset "$version" "$filename" "$tmpdir/squirrel" "binary"; then
    LAST_ERROR_OUTPUT=$(download_failure_output)
    error "$(download_failure_report_line binary)" "$(download_failure_guidance "$filename" binary "$bin_dir")"
  fi
  local binary_url
  binary_url=$(downloaded_url)
  # Only when the mirror answered. The GitHub path is the one almost every
  # install takes, and its output stays byte-identical to before this change.
  if [ "$DOWNLOAD_SOURCE" != "github.com" ]; then
    info "Downloaded from ${DOWNLOAD_SOURCE}"
  fi

  # Verify size. The manifest records each binary's byte count; a truncated download then fails
  # here with a clear size mismatch, not later as a checksum mismatch. A manifest without a size
  # (older releases) or with a value that is not a whole number skips the check.
  CURRENT_STEP="verify_size"
  if [[ "$size" =~ ^[0-9]+$ ]]; then
    local actual_size
    actual_size=$(wc -c < "$tmpdir/squirrel" | tr -d '[:space:]')
    if [ "$actual_size" != "$size" ]; then
      error "Size mismatch: the download is ${actual_size} bytes, the release manifest says ${size}.\n  The download was probably cut short. Run the installer again." \
        "  If it keeps failing, download the binary by hand: https://github.com/${REPO}/releases/tag/${version}"
    fi
  fi

  # Verify checksum
  CURRENT_STEP="verify_checksum"
  log "Verifying checksum..."
  local actual_sha256 expected_sha256
  actual_sha256=$(compute_sha256 "$tmpdir/squirrel")
  actual_sha256=$(printf '%s' "$actual_sha256" | tr '[:upper:]' '[:lower:]')
  expected_sha256=$(printf '%s' "$sha256" | tr '[:upper:]' '[:lower:]')

  if [ "$actual_sha256" != "$expected_sha256" ]; then
    error "Checksum mismatch!\n  Expected: ${expected_sha256}\n  Actual:   ${actual_sha256}"
  fi
  info "Checksum verified: ${expected_sha256:0:16}..."

  # Provenance (#169, repo#5032): a pinned-key signature, else the attestation.
  # In the signed era neither skipping nor sha256 alone is an option.
  SIGNED_ERA_VERSION="$version"
  if release_signed_era "$version"; then SIGNED_ERA=true; else SIGNED_ERA=false; fi
  if ! verify_release_signature "$tmpdir/manifest.json" "$tmpdir/squirrel" "$filename" "$version" "$manifest_url" "$binary_url"; then
    verify_attestation "$tmpdir/squirrel"
  fi

  # Make executable and run self install with bin dir
  chmod +x "$tmpdir/squirrel"

  CURRENT_STEP="self_install"
  log "Running self install..."
  # Tee rather than run bare: the user still sees the output live, and a failure
  # can report what the binary actually said instead of a bare exit code
  # (#1538). PIPESTATUS[0] is the binary's code, not tee's.
  local self_install_log="$tmpdir/self-install.log"
  # The binary is run from here; moved to the fallback staging directory if the temp dir is noexec.
  local exec_binary="$tmpdir/squirrel"
  set +e
  run_self_install "$exec_binary" "$bin_dir" "$self_install_log"
  local rc=$?
  # 126 with "Permission denied" is the shell failing to exec the file, which is what a temp
  # directory mounted noexec (hardened servers, some containers) does. Stage the binary under
  # ~/.squirrel/tmp and try once more; if that fails the same way, say what the cause is.
  if exec_blocked "$rc" "$exec_binary"; then
    warn "Cannot run the downloaded binary from $tmpdir (is it mounted noexec?). Trying ~/.squirrel/tmp..."
    local stage
    stage=$(mkdir -p "$HOME/.squirrel/tmp" 2>/dev/null && mktemp -d "$HOME/.squirrel/tmp/install.XXXXXX" 2>/dev/null)
    if [ -z "$stage" ]; then
      # Not a noexec question: there is nowhere to stage the binary.
      set -e
      CURRENT_STEP="self_install_stage"
      LAST_ERROR_CODE="126"
      LAST_ERROR_OUTPUT=$(tail -n 40 "$self_install_log" 2>/dev/null || true)
      error "Cannot run the downloaded binary from $tmpdir, and ~/.squirrel/tmp could not be created to try again." \
        "  Check that \$HOME/.squirrel is writable (it may be a file, or read only).\n  Or point TMPDIR at a directory that can run programs and run the installer again:\n    TMPDIR=\$HOME/.local/tmp  (mkdir -p it first)"
    fi
    STAGE_TO_CLEAN="$stage"
    if cp "$tmpdir/squirrel" "$stage/squirrel" 2>/dev/null && chmod +x "$stage/squirrel" 2>/dev/null; then
      exec_binary="$stage/squirrel"
      run_self_install "$exec_binary" "$bin_dir" "$self_install_log"
      rc=$?
    fi
    if exec_blocked "$rc" "$exec_binary"; then
      set -e
      CURRENT_STEP="self_install_noexec"
      LAST_ERROR_CODE="126"
      LAST_ERROR_OUTPUT=$(tail -n 40 "$self_install_log" 2>/dev/null || true)
      error "Cannot run the downloaded binary: permission denied (exit 126). A noexec mount is the likely cause." \
        "  Neither $tmpdir nor ~/.squirrel/tmp allows running programs.\n  Point TMPDIR at a directory on a filesystem that does, and run the installer again:\n    TMPDIR=\$HOME/.local/tmp  (mkdir -p it first)\n  or remount the temp directory without noexec."
    fi
  fi
  set -e
  if [ "$rc" -ne 0 ]; then
    # Last lines, not last bytes: a byte cut can split a $HOME path so the
    # scrubber no longer recognizes it and the username rides along. The tail
    # is where the failure is; report_error scrubs and clamps what we pass.
    LAST_ERROR_OUTPUT=$(tail -n 40 "$self_install_log" 2>/dev/null || true)
    LAST_ERROR_CODE="$rc"
    # A signal death is not a self-install bug: the binary never got to fail on
    # its own terms. Move it to its own step so it reports, and fingerprints,
    # apart from real failures (#1654), then finish the install by hand: the
    # file work needs no memory, and a binary that only died mid-install can
    # still run (#2023).
    CURRENT_STEP=$(self_install_step_for_code "$rc")
    if [ "$CURRENT_STEP" = "$SELF_INSTALL_KILLED_STEP" ]; then
      install_by_hand_and_verify "$exec_binary" "$version" "$bin_dir" "$rc"
      return 0
    fi
    error "Self install failed with exit code $rc"
  fi
}

# Recovery path for a signal-killed self install: place the files from bash,
# then prove the binary runs. Reports under self_install_killed when even the
# file work fails, and under verify_binary / verify_binary_killed when the
# files are in place but the binary will not execute.
install_by_hand_and_verify() {
  local binary="$1" version="$2" bin_dir="$3" kill_rc="$4"
  local target link headline macos_version=""

  warn "$(self_install_kill_headline "$kill_rc")"
  log "Finishing the install by hand..."
  if ! target=$(place_release_by_hand "$binary" "$version" "$bin_dir"); then
    LAST_ERROR_CODE="$kill_rc"
    error "$(self_install_kill_headline "$kill_rc")" "$(self_install_kill_guidance "$kill_rc")"
  fi
  link="$bin_dir/squirrel"
  info "Binary: $target"
  info "Link:   $link"

  CURRENT_STEP="$VERIFY_BINARY_STEP"
  log "Checking the installed binary runs..."
  local verify_log="$TMPDIR_TO_CLEAN/verify.log"
  set +e
  "$link" --version 2>&1 | tee "$verify_log"
  local rc=${PIPESTATUS[0]}
  set -e
  if [ "$rc" -ne 0 ]; then
    LAST_ERROR_OUTPUT=$(tail -n 40 "$verify_log" 2>/dev/null || true)
    LAST_ERROR_CODE="$rc"
    CURRENT_STEP=$(verify_binary_step_for_code "$rc")
    # The reported payload is a fixed set of fields (the worker drops anything
    # it does not know), so the macOS release rides in the message itself,
    # which is what Sentry shows as error_line. Without it a darwin kill is
    # indistinguishable from every other darwin kill (#2310). It goes early in
    # the line because the report keeps the message's HEAD when it truncates.
    headline="squirrel is installed but cannot run on this machine"
    if is_darwin; then
      macos_version=$(macos_product_version)
      if [ -n "$macos_version" ]; then
        headline="${headline} (macOS ${macos_version}, exit $rc)"
      else
        headline="${headline} (macOS, exit $rc)"
      fi
    else
      headline="${headline} (exit $rc)"
    fi
    error "${headline}: $target" \
      "$(binary_unrunnable_guidance "$rc" "$target" "$link")"
  fi
  info "Installed by hand after self install was killed (exit $kill_rc); the binary runs."
  echo "  If 'squirrel audit' is killed the same way, the machine needs more memory:" >&2
  echo "    sudo fallocate -l 1G /swapfile && sudo chmod 600 /swapfile && sudo mkswap /swapfile && sudo swapon /swapfile" >&2
}

# Detect the shell and the file it reads at startup (shell:file). Terminal.app
# opens bash as a login shell, which reads ~/.bash_profile and not ~/.bashrc;
# on Linux an interactive bash reads ~/.bashrc. fish gets its own conf.d file,
# which fish sources on startup and which is never anyone else's.
detect_shell_config() {
  local shell="${SHELL:-}" bash_rc
  if [ "$(uname -s 2>/dev/null)" = "Darwin" ]; then
    bash_rc="$HOME/.bash_profile"
  else
    bash_rc="$HOME/.bashrc"
  fi

  if [ -n "$shell" ]; then
    case "$shell" in
      */zsh)  echo "zsh:${ZDOTDIR:-$HOME}/.zshrc" ;;
      */bash) echo "bash:$bash_rc" ;;
      */fish) echo "fish:${XDG_CONFIG_HOME:-$HOME/.config}/fish/conf.d/squirrel.fish" ;;
      */sh)   echo "sh:$HOME/.profile" ;;
      *)      echo "unknown:$HOME/.profile" ;;
    esac
    return
  fi

  # No $SHELL: guess from which startup files exist.
  if [ -f "${ZDOTDIR:-$HOME}/.zshrc" ]; then
    echo "zsh:${ZDOTDIR:-$HOME}/.zshrc"
  elif [ -f "$bash_rc" ]; then
    echo "bash:$bash_rc"
  else
    echo "unknown:$HOME/.profile"
  fi
}

# Same flag semantics as force_mirror_enabled: empty, 0 and false are off.
no_modify_path_enabled() {
  local value
  value=$(printf '%s' "${SQUIRREL_NO_MODIFY_PATH:-}" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]')
  case "$value" in
    "" | 0 | false) return 1 ;;
    *) return 0 ;;
  esac
}

# Same convention as the CLI's detectCi for CI itself: set and not false/0.
ci_enabled() {
  case "${CI:-}" in
    "" | false | 0) return 1 ;;
    *) return 0 ;;
  esac
}

# $HOME-relative display form ("~/.zshrc"), so output never names the user.
tildify() {
  case "$1" in
    "$HOME"/*) printf '~%s' "${1#"$HOME"}" ;;
    *) printf '%s' "$1" ;;
  esac
}

# Set by setup_path, read by main / print_epilogue / the self install stamp:
#   on_path | added | opted_out | ci | failed
PATH_SETUP=""
PATH_SETUP_RC=""
# 1 once the directory was appended to GITHUB_PATH: later CI steps find it, so
# profile instructions would be noise in the log.
PATH_SETUP_GITHUB=0

# Make sure $1 will be on PATH. Appends one marked line to the shell's startup
# file, never rewrites existing content, and does nothing when the directory is
# already on PATH, when the user opted out, or in CI (where GITHUB_PATH, if
# set, is the way to extend PATH for later steps).
setup_path() {
  local bin_dir="$1" shell_info shell_name rc_file line marker="# squirrel"

  if dir_in_path "$bin_dir"; then
    PATH_SETUP="on_path"
    return 0
  fi
  if no_modify_path_enabled; then
    PATH_SETUP="opted_out"
    return 0
  fi
  if ci_enabled; then
    PATH_SETUP="ci"
    if [ -n "${GITHUB_PATH:-}" ]; then
      if printf '%s\n' "$bin_dir" >> "$GITHUB_PATH" 2>/dev/null; then
        info "Added $bin_dir to GITHUB_PATH"
        PATH_SETUP_GITHUB=1
      else
        PATH_SETUP="failed"
      fi
    fi
    return 0
  fi
  # Only the directory the installer itself falls back to is written: it is
  # spelled with $HOME so the profile line survives a moved home.
  if [ "$bin_dir" != "$HOME/.local/bin" ]; then
    PATH_SETUP="opted_out"
    return 0
  fi

  shell_info=$(detect_shell_config)
  shell_name="${shell_info%%:*}"
  rc_file="${shell_info#*:}"
  PATH_SETUP_RC="$rc_file"

  # The profile line keeps a literal $HOME on purpose.
  # shellcheck disable=SC2016
  case "$shell_name" in
    fish) line='fish_add_path $HOME/.local/bin' ;;
    *)    line='export PATH="$HOME/.local/bin:$PATH"' ;;
  esac

  # A profile that already puts the directory on PATH (a non-comment `PATH=` or
  # fish_add_path line naming it, or our own marker) needs no second line. An
  # alias or a function that merely mentions the directory does not count.
  # Only the one profile this shell reads is checked: a line in another login
  # file leaves a harmless second line here.
  if [ -f "$rc_file" ] && { grep -qF "$marker" "$rc_file" 2>/dev/null \
      || grep -v '^[[:space:]]*#' "$rc_file" 2>/dev/null \
        | grep -E '^[[:space:]]*((export|typeset)[[:space:]]+)?PATH=|^[[:space:]]*fish_add_path' \
        | grep -qE '\.local/bin([^A-Za-z0-9_./-]|$)'; }; then
    # Nothing written: it is on PATH for new shells already, so not "added".
    PATH_SETUP="on_path"
    info "$(tildify "$bin_dir") is already on PATH in $(tildify "$rc_file")."
    return 0
  fi

  if mkdir -p "$(dirname "$rc_file")" 2>/dev/null \
      && printf '\n%s\n%s\n' "$marker" "$line" >> "$rc_file" 2>/dev/null; then
    PATH_SETUP="added"
    info "Added $(tildify "$bin_dir") to PATH in $(tildify "$rc_file")."
  else
    PATH_SETUP="failed"
    warn "Could not write $(tildify "$rc_file")"
  fi
}

# Get-started epilogue: lead with the first audit, then `squirrel setup`
# (sign-in, agent skills, defaults), which also ends by offering an audit.
print_epilogue() {
  local version="$1" bin_dir="${2:-}"
  # Same UTF-8 gate as the banner -- CI logs / dumb terminals shouldn't get
  # mojibake from the checkmark glyph either (codex review, #1029).
  local check="✓"
  if ! is_utf8_locale; then
    check="v"
  fi
  echo ""
  echo -e "${GREEN}${check}${NC} squirrel ${version} installed"
  echo ""
  if [ -n "$bin_dir" ] && ! dir_in_path "$bin_dir"; then
    # This shell cannot find squirrel yet: say so before the first command, and
    # give one that works right now.
    local full
    full="$(tildify "$bin_dir")/squirrel"
    if [ -n "$PATH_SETUP_RC" ] && { [ "$PATH_SETUP" = "added" ] || [ "$PATH_SETUP" = "on_path" ]; }; then
      echo "Open a new terminal, or run:  source $(tildify "$PATH_SETUP_RC")"
      echo "Then:  squirrel audit https://your-site.com"
      echo "(or right now:  $full audit https://your-site.com)"
    else
      echo "squirrel is not on your PATH yet. Run your first audit right now:"
      echo ""
      echo "  $full audit https://your-site.com"
    fi
  else
    echo "Run your first audit (crawls the site, scores it, lists exact fixes):"
    echo ""
    echo "  squirrel audit https://your-site.com"
  fi
  echo ""
  echo "Then set up sign-in, agent skills and defaults:  squirrel setup"
  echo "Docs: https://docs.squirrelscan.com"
  echo ""
}

# Print shell profile instructions
print_path_instructions() {
  local bin_dir="$1"
  local shell_info rc_file shell_name

  shell_info=$(detect_shell_config)
  shell_name="${shell_info%%:*}"
  rc_file="${shell_info#*:}"

  warn "$bin_dir is not in your PATH"
  echo ""

  case "$shell_name" in
    fish)
      # The conf.d file setup_path writes may not exist; config.fish does.
      rc_file="${XDG_CONFIG_HOME:-$HOME/.config}/fish/config.fish"
      echo "Add to $rc_file:"
      echo ""
      echo "  fish_add_path $bin_dir"
      echo ""
      echo "Or run now:"
      echo ""
      echo "  echo 'fish_add_path $bin_dir' >> $rc_file && source $rc_file"
      ;;
    zsh|bash|sh|unknown)
      echo "Add to $rc_file:"
      echo ""
      echo "  export PATH=\"$bin_dir:\$PATH\""
      echo ""
      echo "Or run now:"
      echo ""
      echo "  echo 'export PATH=\"$bin_dir:\$PATH\"' >> $rc_file && source $rc_file"
      ;;
  esac

  echo ""
  echo "After updating PATH, verify with: squirrel self doctor"
}

# Refuse to start without a home directory: every path below hangs off $HOME, and under
# `set -u` an unset one used to kill the script mid-run with `HOME: unbound variable`.
check_home() {
  if [ -z "${HOME:-}" ]; then
    error "HOME is not set, so there is nowhere to install to." \
      "  The installer keeps its state under \$HOME/.squirrel, so it needs one even when SQUIRREL_BIN_DIR is set.\n  Set it for this run:  HOME=/home/you ..."
  fi
}

# An absolute path with its `.` and `..` components and repeated or trailing slashes resolved by name
# (no filesystem access): `/usr/..` is `/`, `//` is `/`. A relative path is returned as it is.
lexical_absolute_path() {
  local path="$1" part
  case "$path" in
    /*) ;;
    *) printf '%s' "$path"; return 0 ;;
  esac
  local -a stack=()
  local IFS=/
  set -f # no glob expansion of the parts against the current directory
  for part in $path; do
    case "$part" in
      "" | ".") ;;
      "..") [ "${#stack[@]}" -gt 0 ] && unset 'stack[${#stack[@]}-1]' ;;
      *) stack+=("$part") ;;
    esac
  done
  set +f
  if [ "${#stack[@]}" -eq 0 ]; then
    printf '/'
  else
    printf '/%s' "${stack[*]}"
  fi
}

# Refuse a SQUIRREL_BIN_DIR that is only whitespace or the filesystem root: the installer would
# write the binary link into / (or into a directory named with spaces). Unset or empty means "not
# set", as before.
check_bin_dir_override() {
  [ -n "${SQUIRREL_BIN_DIR:-}" ] || return 0
  # Trim the ends only: a space inside the path is part of it.
  local trimmed="${SQUIRREL_BIN_DIR#"${SQUIRREL_BIN_DIR%%[![:space:]]*}"}" stripped
  trimmed="${trimmed%"${trimmed##*[![:space:]]}"}"
  if [ -z "$trimmed" ]; then
    error "SQUIRREL_BIN_DIR is set but contains only whitespace." \
      "  Unset it to use the default, or give a directory:  SQUIRREL_BIN_DIR=\$HOME/.local/bin"
  fi
  # Resolve `.` and `..` by name before judging it: `/.`, `/..` and `/usr/..` are the root too.
  stripped=$(lexical_absolute_path "$trimmed")
  if [ "$stripped" = "/" ]; then
    error "SQUIRREL_BIN_DIR=$SQUIRREL_BIN_DIR is the filesystem root; refusing to install there." \
      "  Give a directory of your own:  SQUIRREL_BIN_DIR=\$HOME/.local/bin"
  fi
}

main() {
  local channel="${SQUIRREL_CHANNEL:-stable}"

  CURRENT_STEP="check_environment"
  check_home
  check_bin_dir_override

  print_banner

  log "Installing squirrel..."

  CURRENT_STEP="check_deps"
  check_deps

  local platform version bin_dir
  CURRENT_STEP="detect_platform"
  platform=$(detect_platform)
  # Advance the step before logging so a failure after detection is not labelled detect_platform.
  CURRENT_STEP="find_bin_dir"
  log "Detected platform: $platform"

  # musl builds need libstdc++ at runtime — ensure it before we exec the binary.
  case "$platform" in
    *-musl) CURRENT_STEP="musl_runtime"; ensure_musl_runtime ;;
  esac

  # Find writable bin directory in PATH
  CURRENT_STEP="find_bin_dir"
  bin_dir=$(find_bin_dir || true)
  info "Bin directory: $bin_dir"

  # Put it on PATH before self install, which hands the outcome to the CLI's
  # one-time install registration (path_setup).
  CURRENT_STEP="setup_path"
  setup_path "$bin_dir"

  # Version: pinned or latest
  if [ -n "${SQUIRREL_VERSION:-}" ]; then
    version="$SQUIRREL_VERSION"
    INSTALLER_RELEASE_VERSION="${version#v}"
    log "Installing pinned version: $version"
  else
    CURRENT_STEP="fetch_releases"
    version=$(get_latest_version "$channel")
    if [ -z "$version" ]; then
      if [ "$channel" = "stable" ]; then
        error "No stable releases found. Try:\n  SQUIRREL_CHANNEL=beta curl -fsSL ... | bash"
      else
        error "No releases found for channel '$channel'\n  Check: https://github.com/${REPO}/releases"
      fi
    fi
    INSTALLER_RELEASE_VERSION="${version#v}"
    log "Latest version: $version (channel: $channel)"
  fi

  download_and_install "$version" "$platform" "$bin_dir"

  print_epilogue "$version" "$bin_dir"

  # Manual instructions when we did not (or could not) edit a profile
  case "$PATH_SETUP" in
    opted_out|ci|failed)
      if [ "$PATH_SETUP_GITHUB" != 1 ]; then
        echo ""
        print_path_instructions "$bin_dir"
      fi
      ;;
  esac

  echo ""
}

main "$@"
