#!/usr/bin/env bash
set -euo pipefail

# Wrap entire script in { } to prevent partial execution when piped via `curl | sh`.
# If download is interrupted mid-transfer, bash won't execute a truncated script
# because the closing } is missing.
{

# Zenable CLI installer
# Downloads and installs the appropriate Zenable CLI binary for your platform
#
# Usage:
#   curl -fsSL https://cli.zenable.app/install.sh | bash
#   curl -fsSL https://cli.zenable.app/install.sh | bash -s -- --bleeding-edge
#   bash install.sh --no-modify-path -y

# Must be recorded before anything below touches PATH: update_path exports into
# our own process, so $PATH would later report a readiness we cannot deliver to
# the parent shell. Every readiness claim reads this snapshot instead.
ZENABLE_INHERITED_PATH="${PATH-}"

# Configuration
# ZENABLE_INSTALL_DIR overrides the per-user default for machine-wide installs
# (e.g. /usr/local/bin). Placement into an unwritable target escalates through
# sudo — see resolve_placement_privilege.
INSTALL_DIR="${ZENABLE_INSTALL_DIR:-${HOME}/.zenable/bin}"
CUSTOM_INSTALL_DIR=0
[ -n "${ZENABLE_INSTALL_DIR:-}" ] && CUSTOM_INSTALL_DIR=1
ZENABLE_HOME="${HOME}/.zenable"
BASE_URL="${ZENABLE_BASE_URL:-https://cli.zenable.app}"
VERSION="${ZENABLE_VERSION:-latest}"
NO_MODIFY_PATH="${ZENABLE_NO_MODIFY_PATH:-0}"
# When 1, configure PATH only in the user's default shell instead of every
# shell we can detect.
ONLY_DEFAULT_SHELL="${ZENABLE_ONLY_DEFAULT_SHELL:-0}"
# When 1, skip linking the binary into a directory already on the user's PATH.
# Separate from NO_MODIFY_PATH so someone can keep the shell-config edits but
# opt out of the symlink (or vice versa).
NO_PATH_ADOPTION="${ZENABLE_NO_PATH_ADOPTION:-0}"
# Non-interactive mode: explicit env var, or auto-detected from environment
NONINTERACTIVE=0
if [ "${ZENABLE_NONINTERACTIVE:-0}" -eq 1 ] 2>/dev/null; then
  NONINTERACTIVE=1
elif [ "${CI:-}" = "true" ] || [ "${GITHUB_ACTIONS:-}" = "true" ]; then
  NONINTERACTIVE=1
elif [ ! -t 0 ]; then
  NONINTERACTIVE=1
fi
BLEEDING_EDGE="${ZENABLE_BLEEDING_EDGE:-false}"
COSIGN_VERSION="3.1.4"

# Managed-region markers wrapping the PATH line we append to a shell rc. They
# are the ownership signal the rc blocks previously lacked: with an end marker,
# `zenable uninstall` knows exactly which bytes are ours to remove and leaves
# everything the user wrote around them alone. The vocabulary matches the
# instructions-file markers in internal/cmd/install so both artifacts read the
# same and one strip routine handles either.
RC_MANAGED_START="# zenable:managed start — managed by \`zenable\`; \`zenable uninstall\` removes this block"
RC_MANAGED_END="# zenable:managed end"
# The bare header written before markers existed. Kept only so a re-run over a
# pre-marker install recognizes its own work instead of appending a second block.
RC_LEGACY_MARKER="# Zenable CLI"

# Outcome state for the closing message. Plain strings, not arrays: bash 3.2
# (what `curl | bash` gets on macOS) aborts under `set -u` on an empty array.
ADOPTED_DIR=""
ADOPTED_NAMES=""
UNADOPTED_NAMES=""
UPDATED_SHELL_FILES_JOINED=""
UNSUPPORTED_LOGIN_SHELL=""

# Colors for output (only when stdout is a TTY)
if [ -t 1 ]; then
  RED='\033[0;31m'
  GREEN='\033[0;32m'
  YELLOW='\033[1;33m'
  BOLD='\033[1m'
  NC='\033[0m'
else
  RED=''
  GREEN=''
  YELLOW=''
  BOLD=''
  NC=''
fi

# --- Structured logging -----------------------------------------------------
# Write verbose install details into the same file the zenable binary uses so
# users have one place to look when something goes wrong. User-facing output
# (info/warn/error) remains concise; log_detail is log-file only.

# Resolve the zenable log file path for the current platform. Matches the Go
# binary: darwin uses ~/Library/Logs/zenable, linux uses XDG_CACHE_HOME (or
# ~/.cache), windows delegates to PowerShell before we get here.
_zenable_log_file() {
  local plat="${OS:-unknown}"
  local log_dir=""
  case "$plat" in
    darwin)
      log_dir="${HOME}/Library/Logs/zenable"
      ;;
    linux)
      log_dir="${XDG_CACHE_HOME:-${HOME}/.cache}/zenable/logs"
      ;;
    *)
      log_dir="${HOME}/.cache/zenable/logs"
      ;;
  esac
  mkdir -p "$log_dir" 2>/dev/null || return 1
  printf '%s/zenable.log' "$log_dir"
}

# JSON-escape a string for safe embedding in a log line.
_zenable_json_escape() {
  local s="$1"
  s="${s//\\/\\\\}"
  s="${s//\"/\\\"}"
  s="${s//$'\r'/\\r}"
  s="${s//$'\n'/\\n}"
  s="${s//$'\t'/\\t}"
  printf '%s' "$s"
}

# Append one JSON-lines entry to the zenable log file. Silent on failure so
# logging never breaks the install. args_json must already be valid JSON.
_zenable_log_entry() { # <command> <args-json>
  local command="$1" args_json="$2"
  local log_file
  log_file=$(_zenable_log_file) || return 0
  local ts
  ts=$(date -u +"%Y-%m-%dT%H:%M:%SZ" 2>/dev/null || printf '')
  printf '{"timestamp":"%s","command":"%s","args":%s,"platform":"%s","go_version":""}\n' \
    "$ts" "$command" "$args_json" "${OS:-unknown}" >> "$log_file" 2>/dev/null || true
}

_zenable_log_write() {
  local esc_level esc_msg
  esc_level=$(_zenable_json_escape "$1")
  esc_msg=$(_zenable_json_escape "$2")
  _zenable_log_entry "install_script" \
    "$(printf '{"level":"%s","message":"%s"}' "$esc_level" "$esc_msg")"
}

# Logging functions. info/warn/error are user-visible AND logged; log_detail
# is log-file only so stdout stays focused on status milestones.
info() {
  printf "${GREEN}[INFO]${NC} %s\n" "$1"
  _zenable_log_write "info" "$1"
}

warn() {
  printf "${YELLOW}[WARN]${NC} %s\n" "$1" >&2
  _zenable_log_write "warn" "$1"
}

error() {
  printf "${RED}[ERROR]${NC} %s\n" "$1" >&2
  _zenable_log_write "error" "$1"
  exit 1
}

log_detail() {
  _zenable_log_write "info" "$1"
}

# Copy a file aside before we edit it. Mirrors the Go CLI's convention exactly
# (internal/config: $TMPDIR/<name>_<UTC>.bkp, plus a config_backup log entry
# carrying source/backup/reason) so `zenable logs` renders installer backups and
# CLI backups identically and one recovery story covers both.
# Silent no-op when the file does not exist yet, matching BackupConfigFile.
backup_file() { # <path> <reason>
  local path="$1" reason="$2"
  [ -f "$path" ] || return 0

  local ts base tmpdir dest
  ts=$(date -u +"%Y%m%d_%H%M%S_UTC" 2>/dev/null || printf 'unknown')
  base=$(basename "$path")
  tmpdir="${TMPDIR:-/tmp}"
  dest="${tmpdir%/}/${base}_${ts}.bkp"

  cp "$path" "$dest" 2>/dev/null || {
    warn "Could not back up $(tildify "$path"); leaving it unmodified."
    return 1
  }
  _zenable_log_entry "config_backup" "$(printf '{"source":"%s","backup":"%s","reason":"%s"}' \
    "$(_zenable_json_escape "$path")" \
    "$(_zenable_json_escape "$dest")" \
    "$(_zenable_json_escape "$reason")")"
  log_detail "Backed up $(tildify "$path") to ${dest} (${reason})"
  return 0
}

# Replace $HOME prefix with ~ for user-friendly output
tildify() {
  local path="$1"
  # Bash 5 tilde-expands a literal ~ in parameter-substitution replacements,
  # while macOS Bash 3.2 does not. Remove the prefix separately so output is
  # stable across the two installer platforms.
  case "$path" in
    "$HOME")   printf '%s\n' '~' ;;
    "$HOME"/*) printf '~%s\n' "${path#"$HOME"}" ;;
    *)         printf '%s\n' "$path" ;;
  esac
}

# Check if a command exists
command_exists() {
  command -v "$1" >/dev/null 2>&1
}

# Detect which container runtime backs the `docker` CLI.
# Returns: colima | docker-desktop | docker-compatible | "" (no docker)
detect_container_runtime() {
  if ! command_exists docker; then
    echo ""
    return
  fi

  # Fast path: docker context name often reveals the runtime
  local ctx
  ctx=$(docker context show 2>/dev/null || echo "")
  case "$ctx" in
    colima*)
      echo "colima"
      return
      ;;
    desktop-linux|desktop-windows)
      echo "docker-desktop"
      return
      ;;
  esac

  # Fallback: inspect daemon name from docker info
  local daemon_name
  daemon_name=$(docker info --format '{{.Name}}' 2>/dev/null || echo "")
  case "$daemon_name" in
    colima*)
      echo "colima"
      return
      ;;
    docker-desktop|desktop-linux)
      echo "docker-desktop"
      return
      ;;
  esac

  # Docker is present but runtime is unknown (OrbStack, Rancher, etc.)
  echo "docker-compatible"
}

# Prepare a bind-mount directory that the container runtime can access.
# Colima's VM only shares $HOME via virtiofs, so mktemp dirs under
# /private/var/folders (macOS) silently mount as empty inside the container.
# Args: runtime, source_dir, file1 [file2 ...]
# Returns: the host path to mount into the container.
prepare_container_mount_dir() {
  local runtime="$1"
  local source_dir="$2"
  shift 2

  case "$runtime" in
    colima)
      local colima_dir="${HOME}/.zenable/.tmp_cosign_verify_$$"
      mkdir -p "$colima_dir"
      local f
      for f in "$@"; do
        cp "$source_dir/$(basename "$f")" "$colima_dir/"
      done
      echo "$colima_dir"
      ;;
    *)
      echo "$source_dir"
      ;;
  esac
}

# Print usage information
usage() {
  cat <<EOF
${BOLD}Zenable CLI Installer${NC}

${BOLD}USAGE:${NC}
    install.sh [OPTIONS]

${BOLD}OPTIONS:${NC}
    -h, --help              Print this help message
    -y, --yes               Skip confirmation prompts
    --version <VERSION>     Install a specific version (e.g. 2026.02.00)
    --bleeding-edge         Install whichever is newer between latest and beta
    --no-modify-path        Don't modify shell PATH configuration
    --only-default-shell    Configure PATH only in your default shell
                            (default: every shell we can detect)
    --no-path-adoption      Don't link zenable into a directory already on
                            your PATH (skips same-terminal availability)

${BOLD}ENVIRONMENT VARIABLES:${NC}
    ZENABLE_INSTALL_DIR                    Install directory (default: ~/.zenable/bin). An unwritable
                                           target (e.g. /usr/local/bin) escalates placement via sudo
    ZENABLE_BASE_URL                       Override download base URL
    ZENABLE_VERSION                        Set specific version to install (overridden by --version)
    ZENABLE_BLEEDING_EDGE                  Set to "true" to enable bleeding edge mode
    ZENABLE_NO_MODIFY_PATH                 Set to 1 to skip PATH modification
    ZENABLE_ONLY_DEFAULT_SHELL             Set to 1 to configure only the default shell's PATH
    ZENABLE_NO_PATH_ADOPTION               Set to 1 to skip linking into an existing PATH directory
    ZENABLE_NONINTERACTIVE                 Set to 1 to skip all prompts and auto-install integrations
    ZENABLE_DANGEROUSLY_SKIP_VERIFICATION  Set to "true" to skip signature verification
                                           (checksum still enforced)

${BOLD}EXAMPLES:${NC}
    # Install latest stable version
    curl -fsSL https://cli.zenable.app/install.sh | bash

    # Install the newest available (latest or beta, whichever is newer)
    curl -fsSL https://cli.zenable.app/install.sh | bash -s -- --bleeding-edge

    # Install a specific version
    curl -fsSL https://cli.zenable.app/install.sh | bash -s -- --version 2026.02.00

    # Install without modifying PATH
    bash install.sh --no-modify-path

    # Non-interactive install
    ZENABLE_NONINTERACTIVE=1 bash install.sh
EOF
}

# Parse command-line arguments
parse_args() {
  local explicit_version=0

  while [ $# -gt 0 ]; do
    case "$1" in
      -h|--help)
        usage
        exit 0
        ;;
      -y|--yes)
        NONINTERACTIVE=1
        ;;
      --version)
        if [ $# -lt 2 ]; then
          error "--version requires a value"
        fi
        VERSION="$2"
        explicit_version=1
        shift
        ;;
      --bleeding-edge)
        BLEEDING_EDGE=true
        ;;
      --no-modify-path)
        NO_MODIFY_PATH=1
        ;;
      --only-default-shell)
        ONLY_DEFAULT_SHELL=1
        ;;
      --no-path-adoption)
        NO_PATH_ADOPTION=1
        ;;
      *)
        warn "Unknown option: $1 (ignoring)"
        ;;
    esac
    shift
  done

  # Conflict: CLI flags
  if [ "$BLEEDING_EDGE" = "true" ] && [ "$explicit_version" -eq 1 ]; then
    error "--bleeding-edge and --version are mutually exclusive"
  fi

  # Conflict: env vars (ZENABLE_VERSION set to a specific version + bleeding edge)
  if [ "$BLEEDING_EDGE" = "true" ] && [ "$explicit_version" -eq 0 ] && \
     [ -n "${ZENABLE_VERSION:-}" ] && [ "$VERSION" != "latest" ]; then
    error "ZENABLE_BLEEDING_EDGE and ZENABLE_VERSION are mutually exclusive"
  fi
}

# Detect OS
detect_os() {
  case "$(uname -s)" in
    Darwin*)
      echo "darwin"
      ;;
    Linux*)
      echo "linux"
      ;;
    MINGW*|MSYS*|CYGWIN*)
      echo "windows"
      ;;
    *)
      error "Unsupported operating system: $(uname -s)"
      ;;
  esac
}

# Detect architecture
detect_arch() {
  case "$(uname -m)" in
    x86_64|amd64)
      echo "amd64"
      ;;
    arm64|aarch64)
      echo "arm64"
      ;;
    *)
      error "Unsupported architecture: $(uname -m)"
      ;;
  esac
}

# Detect Rosetta 2 translation on macOS and override to native arm64
detect_rosetta() {
  if [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = "1" ]; then
    warn "Rosetta 2 translation detected; installing native arm64 binary"
    ARCH="arm64"
  fi
}

# Detect musl libc on Linux (informational only since CLI is statically linked)
detect_musl() {
  local is_musl=0

  if [ -f /etc/alpine-release ]; then
    is_musl=1
  elif command_exists ldd && ldd --version 2>&1 | grep -qi musl; then
    is_musl=1
  fi

  if [ "$is_musl" -eq 1 ]; then
    log_detail "musl libc detected; binary is statically linked (CGO_ENABLED=0), should work fine"
  fi
}

# Validate required dependencies before downloading anything
check_dependencies() {
  local missing=""

  # curl or wget required for downloads
  if ! command_exists curl && ! command_exists wget; then
    missing="${missing}  - curl or wget (required for downloads)\n"
  fi

  # tar required on linux/darwin for .tar.gz extraction
  if [ "$OS" != "windows" ] && ! command_exists tar; then
    missing="${missing}  - tar (required for archive extraction)\n"
  fi

  if ! command_exists sha256sum && ! command_exists shasum; then
    missing="${missing}  - sha256sum or shasum (required for checksum verification)\n"
  fi

  if [ -n "$missing" ]; then
    printf "${RED}[ERROR]${NC} Missing required dependencies:\n%b" "$missing" >&2
    exit 1
  fi
}

# Check for existing installation and prompt for confirmation
detect_existing() {
  local bin_path="${INSTALL_DIR}/${BINARY_NAME}"

  if [ ! -f "$bin_path" ]; then
    return 0
  fi

  local current_version
  current_version=$("$bin_path" version 2>/dev/null || echo "unknown")
  info "Existing installation found: ${current_version}"
  log_detail "Existing install location: $(tildify "$bin_path")"

  if [ "$NONINTERACTIVE" -eq 1 ]; then
    info "Proceeding with reinstall (non-interactive mode)"
    return 0
  fi

  # Skip prompt if stdin is not a TTY (e.g. piped install)
  if [ ! -t 0 ]; then
    info "Proceeding with reinstall (non-interactive)"
    return 0
  fi

  printf '%b' "${BOLD}Reinstall/upgrade? [y/N]${NC} "
  read -r answer
  case "$answer" in
    [yY]|[yY][eE][sS])
      return 0
      ;;
    *)
      info "Installation cancelled"
      exit 0
      ;;
  esac
}

# Delegate to PowerShell on Windows (MINGW/MSYS/CYGWIN)
delegate_to_powershell() {
  local ps_cmd=""

  if command_exists pwsh; then
    ps_cmd="pwsh"
  elif command_exists powershell.exe; then
    ps_cmd="powershell.exe"
  elif command_exists powershell; then
    ps_cmd="powershell"
  else
    error "PowerShell not found. Please install PowerShell or download the binary manually."
  fi

  info "Windows detected; delegating to PowerShell installer..."

  # Forward values through the environment, never by interpolating them into
  # PowerShell source. The base URL and version are user-controlled; quoting
  # either into -Command would turn an apostrophe into code execution.
  ZENABLE_BASE_URL="$BASE_URL" \
    ZENABLE_VERSION="$VERSION" \
    ZENABLE_BLEEDING_EDGE="$BLEEDING_EDGE" \
    ZENABLE_NO_MODIFY_PATH="$NO_MODIFY_PATH" \
    exec "$ps_cmd" -NoProfile -ExecutionPolicy Bypass -Command \
      "& ([scriptblock]::Create((Invoke-WebRequest -UseBasicParsing (\$env:ZENABLE_BASE_URL + \"/install.ps1\")).Content))"
}

# Verify checksum
verify_checksum() {
  local file="$1"
  local checksum_file="$2"
  local filename
  filename=$(basename "$file")

  if ! command_exists sha256sum && ! command_exists shasum; then
    error "sha256sum or shasum is required for checksum verification"
  fi

  log_detail "Verifying checksum for ${filename}..."

  # Extract expected hash for our specific archive from the combined checksums file
  local expected
  expected=$(grep "  ${filename}$" "$checksum_file" | cut -d' ' -f1)
  if [ -z "$expected" ]; then
    error "No checksum entry found for ${filename} in checksums file"
  fi

  # Compute actual hash
  local actual
  if command_exists sha256sum; then
    actual=$(sha256sum "$file" | cut -d' ' -f1)
  elif command_exists shasum; then
    actual=$(shasum -a 256 "$file" | cut -d' ' -f1)
  fi

  if [ "$expected" != "$actual" ]; then
    error "Checksum verification failed (expected ${expected}, got ${actual})"
  fi

  log_detail "Checksum verification passed"
}

# Silently download cosign binary to a destination path
download_cosign() {
  local dest="$1"
  local cosign_url="https://github.com/sigstore/cosign/releases/download/v${COSIGN_VERSION}/cosign-${OS}-${ARCH}"

  if ! download_file "$cosign_url" "$dest"; then
    return 1
  fi
  chmod +x "$dest"
  return 0
}

# Verify cosign bundle: native cosign → container cosign → downloaded cosign →
# warn-and-continue (no tooling). Intermediate fallback steps are silent; the
# user only sees the method that succeeds, a fatal error when a tool IS present
# but the signature is bad (tampering), or a non-fatal warning when no tooling
# exists at all. A missing/unverifiable signature degrades to a warning; a
# signature that actively fails to verify is always fatal.
run_cosign_verify() {
  local file="$1"
  local bundle_file="$2"

  local cosign_args=(
    verify-blob
    --certificate-identity-regexp "https://github.com/Zenable-io/next-gen-governance/.github/workflows/.*"
    --certificate-oidc-issuer "https://token.actions.githubusercontent.com"
    --bundle "$bundle_file"
    "$file"
  )

  # 1. Try native cosign
  if command_exists cosign; then
    log_detail "Verifying cosign bundle with native cosign..."
    local cosign_out
    if ! cosign_out=$(cosign "${cosign_args[@]}" 2>&1); then
      log_detail "cosign output: ${cosign_out}"
      error "Bundle verification failed"
    fi
    log_detail "cosign output: ${cosign_out}"
    log_detail "Bundle verification passed (native cosign)"
    return 0
  fi

  # 2. Try cosign via container runtime (separate pull + run to distinguish
  #    image pull failures from genuine verification failures)
  local runtime
  runtime=$(detect_container_runtime)
  if [ -n "$runtime" ]; then
    log_detail "Detected container runtime: ${runtime}"
    local docker_image="ghcr.io/sigstore/cosign/cosign:v${COSIGN_VERSION}"
    if docker pull -q "$docker_image" >/dev/null 2>&1; then
      log_detail "Using ${runtime} to validate the cosign signature..."
      local source_dir
      source_dir=$(dirname "$file")

      # Get a mount directory the runtime's VM can access
      local mount_dir
      mount_dir=$(prepare_container_mount_dir "$runtime" "$source_dir" "$file" "$bundle_file")

      # Relax permissions so the container's non-root user can read through the
      # bind-mounted temp directory (mktemp -d creates 700 on Linux).  These are
      # publicly-downloadable artifacts in a short-lived dir cleaned up on EXIT.
      chmod 755 "$mount_dir"
      chmod 644 "$mount_dir"/"$(basename "$file")" "$mount_dir"/"$(basename "$bundle_file")"

      # Mount at a fixed container path to avoid macOS symlink issues
      # (/var/folders → /private/var/folders) that break Docker bind-mounts
      local container_dir="/verify"
      local verify_ok=true
      local docker_out
      if ! docker_out=$(docker run --rm -v "${mount_dir}:${container_dir}:ro" "$docker_image" \
        verify-blob \
        --certificate-identity-regexp "https://github.com/Zenable-io/next-gen-governance/.github/workflows/.*" \
        --certificate-oidc-issuer "https://token.actions.githubusercontent.com" \
        --bundle "${container_dir}/$(basename "$bundle_file")" \
        "${container_dir}/$(basename "$file")" 2>&1); then
        verify_ok=false
      fi
      log_detail "cosign output (${runtime}): ${docker_out}"

      # Clean up colima-specific temp dir
      if [ "$runtime" = "colima" ] && [ "$mount_dir" != "$source_dir" ]; then
        rm -rf "$mount_dir"
      fi

      if [ "$verify_ok" = false ]; then
        error "Bundle verification failed (via ${runtime})"
      fi
      log_detail "Bundle verification passed (via ${runtime})"
      return 0
    fi
  fi

  # 3. Try downloading cosign binary to temp dir
  local cosign_bin="${TEMP_DIR}/cosign"
  if download_cosign "$cosign_bin"; then
    log_detail "Verifying cosign bundle with downloaded cosign binary..."
    local cosign_dl_out
    if ! cosign_dl_out=$("$cosign_bin" "${cosign_args[@]}" 2>&1); then
      log_detail "cosign output: ${cosign_dl_out}"
      error "Bundle verification failed"
    fi
    log_detail "cosign output: ${cosign_dl_out}"
    log_detail "Bundle verification passed (downloaded cosign)"
    return 0
  fi

  # 4. No verification method available — warn and continue.
  # The checksum was already verified above (non-negotiable). The cosign bundle
  # signature is an additional layer we can only check when the tooling exists;
  # absent it we surface a loud warning rather than block the install.
  warn "Your system doesn't have the tools to verify the signature (cosign or a container runtime); skipping signature verification."
  warn "Install cosign or Docker to validate it. The download checksum was still verified."
  return 0
}

# Download file with retry and TLS enforcement
# Only retries on transient errors (5xx, timeouts); 4xx errors fail immediately.
download_file() {
  local url="$1"
  local output="$2"
  local max_retries=3
  local retry=0

  while [ $retry -lt $max_retries ]; do
    if command_exists curl; then
      local http_code
      http_code=$(curl --proto '=https' --tlsv1.2 -fsSL -o "$output" -w '%{http_code}' "$url" 2>/dev/null) && return 0
      # 4xx = permanent (not found, forbidden, etc.) — no point retrying
      if [ -n "$http_code" ] && [ "$http_code" -ge 400 ] 2>/dev/null && [ "$http_code" -lt 500 ] 2>/dev/null; then
        return 1
      fi
    elif command_exists wget; then
      local wget_headers
      wget_headers=$(wget --secure-protocol=TLSv1_2 --server-response -O "$output" "$url" 2>&1 >/dev/null) && return 0
      # Parse HTTP status from wget's server-response headers
      local wget_status
      wget_status=$(echo "$wget_headers" | grep -o 'HTTP/[^ ]* [0-9]*' | tail -1 | awk '{print $2}')
      if [ -n "$wget_status" ] && [ "$wget_status" -ge 400 ] 2>/dev/null && [ "$wget_status" -lt 500 ] 2>/dev/null; then
        return 1
      fi
    else
      error "Neither curl nor wget found. Please install one of them."
    fi

    retry=$((retry + 1))
    if [ $retry -lt $max_retries ]; then
      warn "Download failed, retrying ($retry/$max_retries)..."
      sleep 2
    fi
  done

  return 1
}

# Compare two version strings (with optional pre-release suffix); prints the newer one
# Pre-release versions (e.g. 2026.02.00-beta.16) are older than the same base version (2026.02.00)
newer_version() {
  local v1="$1" v2="$2"

  # Split off pre-release suffix
  local base1="${v1%%-*}" base2="${v2%%-*}"
  local pre1="" pre2=""
  case "$v1" in *-*) pre1="${v1#*-}" ;; esac
  case "$v2" in *-*) pre2="${v2#*-}" ;; esac

  local -a parts1 parts2
  IFS='.' read -ra parts1 <<<"$base1"
  IFS='.' read -ra parts2 <<<"$base2"
  local a1="${parts1[0]:-0}" b1="${parts1[1]:-0}" c1="${parts1[2]:-0}"
  local a2="${parts2[0]:-0}" b2="${parts2[1]:-0}" c2="${parts2[2]:-0}"

  if [ "$a1" -gt "$a2" ] || \
     { [ "$a1" -eq "$a2" ] && [ "$b1" -gt "$b2" ]; } || \
     { [ "$a1" -eq "$a2" ] && [ "$b1" -eq "$b2" ] && [ "$c1" -gt "$c2" ]; }; then
    echo "$v1"
  elif [ "$a1" -lt "$a2" ] || \
       { [ "$a1" -eq "$a2" ] && [ "$b1" -lt "$b2" ]; } || \
       { [ "$a1" -eq "$a2" ] && [ "$b1" -eq "$b2" ] && [ "$c1" -lt "$c2" ]; }; then
    echo "$v2"
  else
    # Base versions equal; release (no pre-release) beats pre-release
    if [ -z "$pre1" ] && [ -n "$pre2" ]; then
      echo "$v1"
    elif [ -n "$pre1" ] && [ -z "$pre2" ]; then
      echo "$v2"
    else
      echo "$v1"
    fi
  fi
}

# Resolve a release channel (latest, beta) to an actual version
# Also extracts the platform-specific archive URL from the pointer JSON
resolve_channel() {
  local channel="$1"
  local pointer_url="${BASE_URL}/zenable/${channel}"
  local temp_file="${TEMP_DIR}/pointer.json"

  log_detail "Resolving '${channel}' channel from ${pointer_url}..."
  if ! download_file "$pointer_url" "$temp_file"; then
    error "Failed to resolve channel '${channel}' from ${pointer_url}"
  fi

  RESOLVED_VERSION=$(grep '"version"' "$temp_file" | head -1 | sed 's/.*: *"//;s/".*//')
  if [ -z "$RESOLVED_VERSION" ]; then
    error "Could not parse version from channel pointer"
  fi

  # Extract platform-specific archive URL from the pointer urls field
  local platform_key="${OS}/${ARCH}"
  RESOLVED_ARCHIVE_URL=$(sed -n "s|.*\"${platform_key}\": *\"\([^\"]*\)\".*|\1|p" "$temp_file" | head -1)

  # Extract bundle URL for the archive from pointer
  local archive_name
  archive_name=$(basename "$RESOLVED_ARCHIVE_URL" 2>/dev/null || true)
  RESOLVED_BUNDLE_URL=""
  if [ -n "$archive_name" ]; then
    RESOLVED_BUNDLE_URL=$(python3 - "$temp_file" "$archive_name" 2>/dev/null <<'PYEOF' || true
import json, sys
try:
    d = json.load(open(sys.argv[1]))
    print(d.get('bundles', {}).get(sys.argv[2], ''))
except Exception:
    pass
PYEOF
)
  fi

  log_detail "Resolved '${channel}' -> ${RESOLVED_VERSION}"
}

# Resolve bleeding edge: pick whichever is newer between latest and beta
resolve_bleeding_edge() {
  resolve_channel "latest"
  local latest_ver="$RESOLVED_VERSION"
  local latest_url="$RESOLVED_ARCHIVE_URL"
  local latest_bundle="$RESOLVED_BUNDLE_URL"

  resolve_channel "beta"
  local beta_ver="$RESOLVED_VERSION"
  local beta_url="$RESOLVED_ARCHIVE_URL"
  local beta_bundle="$RESOLVED_BUNDLE_URL"

  RESOLVED_VERSION=$(newer_version "$latest_ver" "$beta_ver")
  if [ "$RESOLVED_VERSION" = "$latest_ver" ]; then
    RESOLVED_ARCHIVE_URL="$latest_url"
    RESOLVED_BUNDLE_URL="$latest_bundle"
    log_detail "Bleeding edge resolved to latest (${latest_ver}) over beta (${beta_ver})"
  else
    RESOLVED_ARCHIVE_URL="$beta_url"
    RESOLVED_BUNDLE_URL="$beta_bundle"
    log_detail "Bleeding edge resolved to beta (${beta_ver}) over latest (${latest_ver})"
  fi
}

# Extract archive
extract_archive() {
  local archive="$1"
  local dest="$2"

  log_detail "Extracting archive..."

  case "$archive" in
    *.tar.gz)
      if ! tar -xzf "$archive" -C "$dest"; then
        error "Failed to extract archive"
      fi
      ;;
    *.zip)
      if command_exists unzip; then
        if ! unzip -q "$archive" -d "$dest"; then
          error "Failed to extract archive"
        fi
      else
        error "unzip not found. Please install unzip to extract .zip files."
      fi
      ;;
    *)
      error "Unsupported archive format: $archive"
      ;;
  esac
}

# Every shell we know how to configure, most common first. The loop in
# update_path walks this list; anything absent from it falls through to the
# unsupported-shell warning rather than being silently ignored.
SUPPORTED_SHELLS="sh bash zsh fish ksh dash ash mksh tcsh csh nu elvish"

# Map a shell to the syntax family its PATH setup is written in. One family may
# cover several shells (every POSIX-compatible shell shares one env file), so
# callers key off the family and never off the shell name.
# Returns non-zero for shells we cannot express PATH setup in.
shell_family() {
  case "$1" in
    sh|bash|zsh|ksh|ksh93|dash|ash|mksh|pdksh) echo "posix" ;;
    fish)                                      echo "fish" ;;
    tcsh|csh)                                  echo "csh" ;;
    nu|nushell)                                echo "nu" ;;
    elvish|elv)                                echo "elvish" ;;
    *)                                         return 1 ;;
  esac
}

# Resolve the rc/profile file a shell reads for PATH. Echoes the path; where a
# shell has several candidates we prefer one that already exists, else the
# conventional default (the caller creates it).
# Returns non-zero for shells we don't manage (so callers can skip them).
shell_rc_path() {
  case "$1" in
    bash)
      if [ -f "${HOME}/.bashrc" ]; then
        echo "${HOME}/.bashrc"
      elif [ -f "${HOME}/.bash_profile" ]; then
        echo "${HOME}/.bash_profile"
      else
        echo "${HOME}/.bashrc"
      fi
      ;;
    zsh)  echo "${ZDOTDIR:-${HOME}}/.zshrc" ;;
    fish) echo "${HOME}/.config/fish/config.fish" ;;
    # dash/ash/mksh have no rc of their own for non-login shells; ~/.profile is
    # the file every POSIX shell agrees to read at login, so they share it with
    # plain sh. Writing it once is why write_path_to_shell dedups by rc path.
    sh|dash|ash) echo "${HOME}/.profile" ;;
    ksh|ksh93|pdksh|mksh)
      if [ -f "${HOME}/.kshrc" ]; then
        echo "${HOME}/.kshrc"
      else
        echo "${HOME}/.profile"
      fi
      ;;
    tcsh)
      if [ -f "${HOME}/.tcshrc" ]; then
        echo "${HOME}/.tcshrc"
      else
        echo "${HOME}/.cshrc"
      fi
      ;;
    csh) echo "${HOME}/.cshrc" ;;
    # Nushell's config dir is platform-specific and it exposes no rc under $HOME
    # on macOS, so mirror its documented default per platform.
    nu|nushell)
      if [ "${OS:-}" = "darwin" ]; then
        echo "${HOME}/Library/Application Support/nushell/env.nu"
      else
        echo "${XDG_CONFIG_HOME:-${HOME}/.config}/nushell/env.nu"
      fi
      ;;
    elvish|elv) echo "${XDG_CONFIG_HOME:-${HOME}/.config}/elvish/rc.elv" ;;
    *) return 1 ;;
  esac
}

# Recognize only the exact two-line block emitted before end markers existed.
# A file-wide marker/PATH match can collide with unrelated user prose.
legacy_path_block_present() { # <rc> <bin-dir>
  local rc="$1" bin_dir="$2"
  [ -f "$rc" ] || return 1
  awk \
    -v marker="$RC_LEGACY_MARKER" \
    -v posix="export PATH=\"${bin_dir}:\$PATH\"" \
    -v fish="set --export PATH ${bin_dir} \$PATH" \
    'previous == marker && ($0 == posix || $0 == fish) { found = 1 }
     { previous = $0 }
     END { exit !found }' "$rc"
}

# Append the PATH setup for bin_dir to one shell's rc file, idempotently, in
# that shell family's own syntax. Creates the file (and parent dir) when missing.
# Records freshly-written files in the UPDATED_SHELL_FILES array for the caller's
# summary line.
write_path_to_shell() {
  local shell_name="$1" bin_dir="$2"
  local rc family
  rc="$(shell_rc_path "$shell_name")" || return 0
  family="$(shell_family "$shell_name")" || return 0

  # The file is deliberately NOT pre-created here: the greps below tolerate a
  # missing file and the append creates it, so a fresh rc never produces a
  # backup of the empty file we just made ourselves. Matches BackupConfigFile's
  # "no file, no backup" contract.
  mkdir -p "$(dirname "$rc")"

  # Already configured? The marker is the signal; the legacy bare header is
  # accepted too so a re-run over a pre-marker install recognizes its own work
  # instead of appending a second block. Legacy detection pairs the header with
  # bin_dir so an unrelated "# Zenable CLI" comment can't suppress the write.
  if grep -qF "$RC_MANAGED_START" "$rc" 2>/dev/null; then
    log_detail "PATH already configured in $(tildify "$rc")"
    return 0
  fi
  if legacy_path_block_present "$rc" "$bin_dir"; then
    log_detail "PATH already configured in $(tildify "$rc") (pre-marker block)"
    return 0
  fi

  # Never append without a copy aside first — this is the user's own dotfile.
  backup_file "$rc" "path_install" || return 0

  log_detail "Adding $(tildify "$bin_dir") to $(tildify "$rc") (${family} syntax)"
  {
    echo ""
    echo "$RC_MANAGED_START"
    case "$family" in
      fish)
        echo "set --export PATH ${bin_dir} \$PATH"
        ;;
      csh)
        echo "setenv PATH \"${bin_dir}:\$PATH\""
        ;;
      nu)
        # $env.PATH is a list, not a delimited string; `uniq` keeps a re-sourced
        # config from stacking duplicate entries.
        echo "\$env.PATH = (\$env.PATH | prepend \"${bin_dir}\" | uniq)"
        ;;
      elvish)
        echo "if (not (has-value \$paths \"${bin_dir}\")) {"
        echo "  set paths = [\"${bin_dir}\" \$@paths]"
        echo "}"
        ;;
      *)
        echo "export PATH=\"${bin_dir}:\$PATH\""
        ;;
    esac
    echo "$RC_MANAGED_END"
  } >> "$rc"
  UPDATED_SHELL_FILES+=("$rc")
}

# Update PATH in shell config
update_path() {
  local bin_dir="$1"

  # In GitHub Actions, write to GITHUB_PATH and update current session
  if [ -n "${GITHUB_PATH:-}" ]; then
    echo "${bin_dir}" >> "${GITHUB_PATH}"
    export PATH="${bin_dir}:${PATH}"
    log_detail "Added $(tildify "$bin_dir") to GITHUB_PATH"
    return 0
  fi

  # Pick target shells. Default: every shell we can detect (its binary is on
  # PATH, its rc already exists, or it is the login shell). --only-default-shell
  # narrows to just the login shell. We DON'T early-return when bin_dir is
  # already on the live PATH — a re-run must still backfill shells whose rc was
  # never written (each write is idempotent per-file).
  local default_shell="${SHELL##*/}"
  local target_shells="" s rc

  # Record a login shell we cannot configure so the closing message can say so
  # explicitly. Staying silent here is what leaves someone on an exotic shell
  # believing the install finished cleanly when nothing was wired up.
  if ! shell_family "$default_shell" >/dev/null 2>&1; then
    UNSUPPORTED_LOGIN_SHELL="$default_shell"
  fi

  if [ "$ONLY_DEFAULT_SHELL" -eq 1 ]; then
    if shell_rc_path "$default_shell" >/dev/null 2>&1; then
      target_shells="$default_shell"
    fi
  else
    for s in $SUPPORTED_SHELLS; do
      rc="$(shell_rc_path "$s")" || continue
      if [ "$s" = "$default_shell" ] || command_exists "$s" || [ -f "$rc" ]; then
        target_shells="${target_shells}${s} "
      fi
    done
  fi

  UPDATED_SHELL_FILES=()
  for s in $target_shells; do
    write_path_to_shell "$s" "$bin_dir"
  done

  # Add to current session (only if absent)
  case ":${PATH}:" in
    *:"${bin_dir}":*) ;;
    *) export PATH="${bin_dir}:${PATH}" ;;
  esac

  if [ "${#UPDATED_SHELL_FILES[@]}" -gt 0 ]; then
    local joined=""
    for rc in "${UPDATED_SHELL_FILES[@]}"; do
      joined="${joined}$(tildify "$rc"), "
    done
    joined="${joined%, }"
    UPDATED_SHELL_FILES_JOINED="$joined"
    info "Added $(tildify "$bin_dir") to PATH in: ${joined}"
    # Whether a new terminal is actually needed is decided by print_next_steps,
    # which compares against the inherited PATH snapshot. Claiming it here would
    # be a guess, and it is wrong whenever the binary is already reachable.
  elif [ -n "$target_shells" ]; then
    log_detail "PATH already configured for detected shells"
  fi
}

# Is dir an entry on the given PATH string? Entry-wise, not substring: a
# substring test also matches a directory that merely has this one as a prefix.
# Runs in a subshell so the IFS and glob changes never leak to the caller.
path_contains_dir() ( # <dir> <path-string>
  local want="$1" entry
  while [ "$want" != "/" ] && [ "${want%/}" != "$want" ]; do
    want="${want%/}"
  done
  IFS=:
  set -f
  for entry in $2; do
    while [ "$entry" != "/" ] && [ "${entry%/}" != "$entry" ]; do
      entry="${entry%/}"
    done
    if [ "$entry" = "$want" ]; then
      exit 0
    fi
  done
  exit 1
)

# May we drop a symlink into this directory? It must already be on the PATH the
# user's shell handed us (that is the entire point — a directory we would have to
# add to PATH gets us nothing the rc files don't), and it must be ours to write.
dir_is_adoptable() { # <dir>
  local dir="$1"

  path_contains_dir "$dir" "$ZENABLE_INHERITED_PATH" || return 1
  [ -d "$dir" ] || return 1
  [ -w "$dir" ] || return 1
  # Owned by us. This is what keeps us out of root-owned /usr/local/bin on a
  # normal account without ever prompting for sudo from a `curl | bash` pipe.
  [ -O "$dir" ] || return 1
  # World-writable means anyone can swap our symlink for their own binary.
  if [ -n "$(find "$dir" -maxdepth 0 -perm -0002 2>/dev/null)" ]; then
    return 1
  fi
  # A Homebrew prefix is package-manager territory: `brew` prunes and relinks it,
  # and an unmanaged file there is both fragile and rude. Detecting the sibling
  # Cellar covers every prefix without hardcoding Intel vs Apple Silicon paths.
  if [ -d "${dir%/bin}/Cellar" ]; then
    return 1
  fi
  # Our own install dir is already handled by the rc files.
  case "$dir" in
    "${ZENABLE_HOME}"|"${ZENABLE_HOME}"/*) return 1 ;;
  esac
  return 0
}

# An allowlist on purpose, and it must stay one: a denylist would have to
# enumerate Homebrew, Nix, cargo, bun, go, pyenv, asdf and whatever ships next,
# and every miss drops a symlink inside a foreign tool's managed tree.
path_adoption_candidates() {
  printf '%s\n' \
    "${HOME}/.local/bin" \
    "${HOME}/bin" \
    "/usr/local/bin"
}

find_path_adoption_dir() {
  local cand
  # A here-doc, not a pipeline: a pipeline runs the loop in a subshell, and a
  # space in $HOME would split a word-splitting loop. This is safe for both.
  while IFS= read -r cand; do
    [ -n "$cand" ] || continue
    if dir_is_adoptable "$cand"; then
      echo "$cand"
      return 0
    fi
  done <<EOF
$(path_adoption_candidates)
EOF
  return 1
}

# Link one name from the install dir into an already-on-PATH directory.
# Returns 0 when the link is in place, 1 when we deliberately left something
# alone. Never clobbers anything we did not create.
link_into_path_dir() { # <bin_dir> <target_dir> <name>
  local bin_dir="$1" target_dir="$2" name="$3"
  local src="${bin_dir}/${name}" dest="${target_dir}/${name}"
  local current resolved resolved_dir

  if [ -L "$dest" ]; then
    current="$(readlink "$dest" 2>/dev/null || echo "")"
    resolved="$current"
    case "$resolved" in
      /*) ;;
      *)
        # Resolve relative links lexically while their target directory exists.
        # readlink returns the stored text, but ownership is about where it
        # points; the Go doctor/uninstaller uses the same rule.
        resolved_dir="$(cd "${target_dir}/$(dirname "$resolved")" 2>/dev/null && pwd -L)" || resolved_dir=""
        if [ -n "$resolved_dir" ]; then
          resolved="${resolved_dir}/$(basename "$resolved")"
        fi
        ;;
    esac
    case "$resolved" in
      "${bin_dir}/"*|"${ZENABLE_HOME}/"*)
        # Ours: refresh so an older or relative link is normalized.
        ln -sfn "$src" "$dest" 2>/dev/null || return 1
        log_detail "Refreshed ${dest} -> ${src}"
        return 0
        ;;
      *)
        log_detail "Leaving foreign symlink alone: ${dest} -> ${current}"
        return 1
        ;;
    esac
  fi

  if [ -e "$dest" ]; then
    # A real file someone else owns. `z` in particular is the command name of
    # zoxide, autojump and rupa/z, so this branch is load-bearing, not theoretical.
    log_detail "Leaving existing file alone: ${dest}"
    return 1
  fi

  # No -f: letting the create fail when something appeared underneath us is the
  # atomic guard against clobbering a file another process just wrote.
  ln -s "$src" "$dest" 2>/dev/null || return 1
  log_detail "Linked ${dest} -> ${src}"
  return 0
}

# Make zenable resolvable in the terminal the user is already sitting in, by
# linking it into a directory their shell's PATH already contains. The only
# mechanism that reaches the current shell (exporting PATH is invisible to the
# parent, rc files wait for a new shell), and the only one that is shell-agnostic.
adopt_into_path_dir() { # <bin_dir>
  local bin_dir="$1" target_dir name

  target_dir="$(find_path_adoption_dir)" || return 0

  for name in "$BINARY_NAME" z; do
    if link_into_path_dir "$bin_dir" "$target_dir" "$name"; then
      ADOPTED_NAMES="${ADOPTED_NAMES}${name} "
    else
      UNADOPTED_NAMES="${UNADOPTED_NAMES}${name} "
    fi
  done

  if [ -n "$ADOPTED_NAMES" ]; then
    ADOPTED_DIR="$target_dir"
    local pretty=""
    for name in $ADOPTED_NAMES; do
      if [ -z "$pretty" ]; then pretty="$name"; else pretty="${pretty} and ${name}"; fi
    done
    info "Linked ${pretty} into $(tildify "$target_dir") (already on your PATH)"
  fi
  if [ -n "$UNADOPTED_NAMES" ]; then
    local skipped
    for skipped in $UNADOPTED_NAMES; do
      warn "Left the existing $(tildify "${target_dir}/${skipped}") in place; not overwriting it."
    done
  fi
}

# Would the user's own shell resolve this installed binary right now? Directory
# membership is insufficient: an older or foreign zenable earlier on PATH can
# shadow both the canonical directory and a newly adopted launcher.
zenable_resolves_in_user_shell() (
  local resolved
  PATH="$ZENABLE_INHERITED_PATH"
  hash -r
  resolved="$(command -v "$BINARY_NAME" 2>/dev/null)" || exit 1
  [ -n "$resolved" ] && [ "$resolved" -ef "${INSTALL_DIR}/${BINARY_NAME}" ]
)

# How to invoke zenable in a command we print. Bare name when the user's shell
# already resolves it, absolute path otherwise, so every command we suggest is
# pasteable as-is rather than only after some other step.
zenable_cmd() {
  if zenable_resolves_in_user_shell; then
    echo "$BINARY_NAME"
  else
    tildify "${INSTALL_DIR}/${BINARY_NAME}"
  fi
}

# The closing message. Says what is true, having checked, rather than telling
# everyone to open a new terminal whether or not they need to.
print_next_steps() {
  local cmd
  cmd="$(zenable_cmd)"

  echo ""
  if [ -n "${GITHUB_PATH:-}" ]; then
    info "Added $(tildify "$INSTALL_DIR") to GITHUB_PATH; zenable resolves in later steps of this job."
  elif zenable_resolves_in_user_shell; then
    info "zenable is ready to use in this terminal."
  else
    # Nothing on the inherited PATH was ours to write, so this terminal cannot
    # be fixed from here. The rc files still cover every terminal after it.
    info "zenable is installed at $(tildify "${INSTALL_DIR}/${BINARY_NAME}")"
    if [ -n "$UPDATED_SHELL_FILES_JOINED" ]; then
      info "Open a new terminal to use it, or run it by full path in this one."
    else
      info "Add $(tildify "$INSTALL_DIR") to your PATH, or run it by full path."
    fi
  fi

  # An unconfigurable login shell is the one case where the install genuinely is
  # incomplete. Say so plainly instead of letting it look like a clean finish.
  if [ -n "$UNSUPPORTED_LOGIN_SHELL" ]; then
    echo ""
    warn "Your login shell (${UNSUPPORTED_LOGIN_SHELL}) is not one this installer can configure."
    if [ -n "$ADOPTED_DIR" ]; then
      warn "zenable was linked into $(tildify "$ADOPTED_DIR"), which is already on your PATH, so it should work."
    else
      warn "Add $(tildify "$INSTALL_DIR") to your PATH using ${UNSUPPORTED_LOGIN_SHELL}'s own syntax,"
      warn "or run the binary by full path: $(tildify "${INSTALL_DIR}/${BINARY_NAME}")"
    fi
  fi

  echo ""
  echo "Next steps:"
  printf '  Review this project      %s check\n' "$cmd"
  printf '  Set up a project         %s install --project\n' "$cmd"
  echo ""
  echo "For more information, see https://www.zenable.app/docs"
}

# Download baseline configuration file (skip if already exists)
write_baseline_config() {
  local config_dir="${HOME}/.zenable"
  local config_file="${config_dir}/zenable.yaml"

  if [ -f "$config_file" ]; then
    log_detail "Configuration already exists at $(tildify "$config_file")"
    return 0
  fi

  mkdir -p "$config_dir"

  local config_url="${BASE_URL}/zenable/${VERSION}/default_zenable.yaml"
  log_detail "Downloading default configuration from ${config_url}..."
  if download_file "$config_url" "$config_file"; then
    log_detail "Configuration written to $(tildify "$config_file")"
  else
    error "Could not download default configuration from ${config_url}"
  fi
}

# Record that shell completions are available (detail-only; mentioned in
# `zenable --help` so it doesn't need to clutter the install output).
# --- Privileged placement ----------------------------------------------------
# place() escalates ONLY the placement commands per PLACEMENT_SUDO; download,
# checksum, and signature steps always run unprivileged. Empty (the per-user
# default) keeps the common path byte-identical to pre-ZENABLE_INSTALL_DIR.
PLACEMENT_SUDO=""

place() { # <command...>
  case "$PLACEMENT_SUDO" in
    sudo-n) sudo -n "$@" ;;
    sudo) sudo "$@" ;;
    *) "$@" ;;
  esac
}

# Walk up from a (possibly not-yet-created) directory to its nearest existing
# ancestor — the directory mkdir -p would actually need write access to.
nearest_existing_dir() { # <dir>
  local dir="$1"
  while [ ! -d "$dir" ]; do
    local parent
    parent=$(dirname "$dir")
    [ "$parent" = "$dir" ] && break
    dir="$parent"
  done
  printf '%s' "$dir"
}

placement_needs_privilege() {
  local probe
  probe=$(nearest_existing_dir "$INSTALL_DIR")
  [ ! -w "$probe" ]
}

# Mirrors the CLI's elevation ladder: a non-interactive sudo grant first (it
# can never hang a pipe), then interactive sudo when a human is at a terminal
# — sudo prompts on the TTY itself, so the password never passes through this
# script — else a clean error BEFORE any download is spent.
resolve_placement_privilege() {
  placement_needs_privilege || return 0
  if ! command_exists sudo; then
    error "Install directory $(tildify "$INSTALL_DIR") is not writable and sudo is unavailable. Re-run as root, or set ZENABLE_INSTALL_DIR to a writable location."
  fi
  if sudo -n true 2>/dev/null; then
    PLACEMENT_SUDO="sudo-n"
    log_detail "Placement into ${INSTALL_DIR} via non-interactive sudo"
    return 0
  fi
  if [ "$NONINTERACTIVE" -ne 1 ] && [ -t 0 ]; then
    info "$(tildify "$INSTALL_DIR") is not writable by your user; elevating placement with sudo (sudo may prompt for your password)"
    if sudo -v; then
      PLACEMENT_SUDO="sudo"
      return 0
    fi
    error "sudo authentication failed; cannot write $(tildify "$INSTALL_DIR")"
  fi
  error "Install directory $(tildify "$INSTALL_DIR") is not writable by your user. Re-run with sudo, prime credentials first ('sudo -v'), or set ZENABLE_INSTALL_DIR to a writable location."
}

setup_completions() {
  local shell_name
  case "${SHELL:-}" in
    */bash) shell_name="bash" ;;
    */zsh)  shell_name="zsh" ;;
    */fish) shell_name="fish" ;;
    *)      return 0 ;;
  esac

  log_detail "Shell completions available. Run: zenable completion ${shell_name}"
}

# Main installation logic
main() {
  parse_args "$@"

  # Detect platform
  OS=$(detect_os)

  # Delegate to PowerShell on Windows
  if [ "$OS" = "windows" ]; then
    delegate_to_powershell
    # exec replaces the process; this line is unreachable
  fi

  ARCH=$(detect_arch)

  # Platform-specific detection
  if [ "$OS" = "darwin" ]; then
    detect_rosetta
  fi
  if [ "$OS" = "linux" ]; then
    detect_musl
  fi

  info "Installing Zenable CLI for ${OS}/${ARCH}..."
  log_detail "Install started (OS=${OS}, ARCH=${ARCH}, NONINTERACTIVE=${NONINTERACTIVE}, BLEEDING_EDGE=${BLEEDING_EDGE})"

  # Check dependencies before downloading
  check_dependencies

  # Resolve placement privilege before downloading, so an unwritable
  # ZENABLE_INSTALL_DIR fails fast instead of after the archive fetch.
  resolve_placement_privilege

  # Determine archive format and binary name
  ARCHIVE_EXT=".tar.gz"
  BINARY_NAME="zenable"
  if [ "$OS" = "windows" ]; then
    ARCHIVE_EXT=".zip"
    BINARY_NAME="zenable.exe"
  fi

  # Check for existing installation
  detect_existing

  # Create temp directory with cleanup trap (needed for channel resolution)
  TEMP_DIR=$(mktemp -d)
  # Resolve symlinks so Docker bind-mounts work on macOS (/var → /private/var)
  TEMP_DIR=$(cd "$TEMP_DIR" && pwd -P)
  trap 'rm -rf "$TEMP_DIR"' EXIT

  # Resolve version
  RESOLVED_ARCHIVE_URL=""
  RESOLVED_BUNDLE_URL=""
  if [ "$BLEEDING_EDGE" = "true" ]; then
    resolve_bleeding_edge
    VERSION="$RESOLVED_VERSION"
  elif [ "$VERSION" = "latest" ]; then
    resolve_channel "latest"
    VERSION="$RESOLVED_VERSION"
  fi
  # Otherwise VERSION is a specific version string, used as-is

  # Use archive URL from pointer JSON when available (handles promoted
  # releases where filenames don't match the target version).  Fall back
  # to constructing the URL for direct version installs.
  if [ -n "$RESOLVED_ARCHIVE_URL" ]; then
    ARCHIVE_URL="$RESOLVED_ARCHIVE_URL"
    ARCHIVE_NAME=$(basename "$ARCHIVE_URL")
    # Extract the embedded version from the archive filename (e.g. "2026.02.00-alpha.9"
    # from "zenable_2026.02.00-alpha.9_darwin_arm64.tar.gz") for the checksums file
    ARTIFACT_VERSION=$(echo "$ARCHIVE_NAME" | sed 's/^zenable_//;s/_[a-z].*$//')
    if [ -z "$ARTIFACT_VERSION" ]; then
      error "Could not extract artifact version from archive name: ${ARCHIVE_NAME}"
    fi
  else
    ARCHIVE_NAME="zenable_${VERSION}_${OS}_${ARCH}${ARCHIVE_EXT}"
    ARCHIVE_URL="${BASE_URL}/zenable/${VERSION}/${ARCHIVE_NAME}"
    ARTIFACT_VERSION="$VERSION"
  fi
  CHECKSUM_URL="${BASE_URL}/zenable/${VERSION}/zenable_${ARTIFACT_VERSION}_checksums.txt"
  # Use pointer-provided URLs; fall back to convention-based URLs
  BUNDLE_URL="${RESOLVED_BUNDLE_URL:-${ARCHIVE_URL}.bundle}"

  # Download archive
  info "Downloading zenable v${VERSION}..."
  log_detail "Archive URL: ${ARCHIVE_URL}"
  ARCHIVE_PATH="${TEMP_DIR}/${ARCHIVE_NAME}"
  if ! download_file "$ARCHIVE_URL" "$ARCHIVE_PATH"; then
    error "Failed to download archive from ${ARCHIVE_URL}"
  fi

  # Download and verify checksum (always required)
  CHECKSUM_PATH="${TEMP_DIR}/zenable_${ARTIFACT_VERSION}_checksums.txt"
  if ! download_file "$CHECKSUM_URL" "$CHECKSUM_PATH"; then
    error "Failed to download checksum file from ${CHECKSUM_URL}"
  fi
  verify_checksum "$ARCHIVE_PATH" "$CHECKSUM_PATH"

  # Verify the cosign signature (best-effort on Linux/macOS — needs cosign or a
  # container runtime). Missing tooling or a missing bundle degrades to a
  # warning; a signature that actively fails to verify stays fatal (tampering).
  if [ "${ZENABLE_DANGEROUSLY_SKIP_VERIFICATION:-}" = "true" ]; then
    warn "Signature verification skipped (ZENABLE_DANGEROUSLY_SKIP_VERIFICATION=true)"
  else
    BUNDLE_PATH="${TEMP_DIR}/${ARCHIVE_NAME}.bundle"
    if download_file "$BUNDLE_URL" "$BUNDLE_PATH" 2>/dev/null; then
      run_cosign_verify "$ARCHIVE_PATH" "$BUNDLE_PATH"
    else
      warn "Signature bundle could not be downloaded; skipping signature verification."
      warn "The download checksum was still verified."
    fi
  fi

  # Create installation directory
  place mkdir -p "$INSTALL_DIR"

  # Write baseline configuration
  write_baseline_config

  # Extract archive
  extract_archive "$ARCHIVE_PATH" "$TEMP_DIR"

  # Find and install binary
  BINARY_PATH=$(find "$TEMP_DIR" -name "$BINARY_NAME" -type f | head -n 1)
  if [ -z "$BINARY_PATH" ]; then
    error "Binary not found in archive"
  fi

  # cp (not install) so an overwrite writes through the existing inode and a
  # customized owner on the installed binary is preserved.
  place cp "$BINARY_PATH" "${INSTALL_DIR}/${BINARY_NAME}"
  place chmod +x "${INSTALL_DIR}/${BINARY_NAME}"
  log_detail "Installed binary at $(tildify "${INSTALL_DIR}/${BINARY_NAME}")"

  # Create 'z' shorthand alias via symlink
  place ln -sf "$BINARY_NAME" "${INSTALL_DIR}/z"
  log_detail "Created 'z' alias -> zenable"

  # Update PATH (unless opted out)
  if [ "$CUSTOM_INSTALL_DIR" -eq 1 ] && path_contains_dir "$INSTALL_DIR" "$ZENABLE_INHERITED_PATH"; then
    # A custom dir like /usr/local/bin is usually already resolvable; rc edits
    # and adoption symlinks would only add noise.
    info "$(tildify "$INSTALL_DIR") is already on your PATH; skipping shell configuration"
  elif [ "$NO_MODIFY_PATH" -ne 1 ]; then
    update_path "$INSTALL_DIR"
    # Only reaches the user's *current* shell; the rc edits above only reach new
    # ones. Both run, because neither alone covers both cases.
    if [ "$NO_PATH_ADOPTION" -ne 1 ]; then
      adopt_into_path_dir "$INSTALL_DIR"
    fi
  else
    info "Skipping PATH modification (--no-modify-path)"
  fi

  # Verify installation
  if ZENABLE_INVOCATION_SOURCE=installer "${INSTALL_DIR}/${BINARY_NAME}" version >/dev/null 2>&1; then
    INSTALLED_VERSION=$(ZENABLE_INVOCATION_SOURCE=installer "${INSTALL_DIR}/${BINARY_NAME}" version 2>&1 | sed 's/^zenable *//')
    setup_completions
    echo ""
    info "Successfully installed Zenable CLI v${INSTALLED_VERSION}!"
    echo ""

    # Prompt to install integrations
    if [ "$NONINTERACTIVE" -eq 1 ]; then
      info "Installing integrations non-interactively..."
      # Propagate non-interactive intent to every Zenable subprocess so the
      # auth helpers fail fast with the canonical login prompt instead of
      # hanging on an OAuth flow no one is going to complete.
      ZENABLE_NONINTERACTIVE=1 ZENABLE_INVOCATION_SOURCE=installer "${INSTALL_DIR}/${BINARY_NAME}" install -y
    elif [ -t 0 ]; then
      printf '%b' "${BOLD}Would you like to install the Zenable integrations? [Y/n]${NC} "
      read -r answer
      case "$answer" in
        [nN])
          echo ""
          info "No problem; you can install them globally by running '$(zenable_cmd) install' or in a project with '$(zenable_cmd) install --project'"
          ;;
        *)
          ZENABLE_INVOCATION_SOURCE=installer "${INSTALL_DIR}/${BINARY_NAME}" install
          ;;
      esac
    else
      info "Install integrations globally with '$(zenable_cmd) install' or in a project with '$(zenable_cmd) install --project'"
    fi

    print_next_steps
  else
    warn "Installation completed but binary verification failed"
    info "Binary installed at: $(tildify "${INSTALL_DIR}/${BINARY_NAME}")"
  fi
}

# Run main function. Skipped when the script is sourced for tests
# (ZENABLE_INSTALL_SH_LIB=1) so the shell functions can be exercised in
# isolation without performing an install.
if [ -z "${ZENABLE_INSTALL_SH_LIB:-}" ]; then
  main "$@"
fi

}
