#!/usr/bin/env bash
# Install the latest CAM local release package from the official release service.
#
# Local deployments wait at most 1800 seconds for the machine-wide lock and
# report its holder every 10 seconds. See scripts/lib/local-deploy-lock.sh for
# test-only environment overrides and stale-owner semantics.

set -euo pipefail

# 由 volta shim node 启动的 bridge 会把 volta 的递归保护变量传进来；带着它
# 执行任何 volta shim（npm/node、cam install 派生的 node）都会被
# 判为递归调用而失败（"Node is not available"，exit 126）。先清掉它。
unset _VOLTA_TOOL_RECURSION

# `curl -fsSL ... | bash` runs this script from stdin: there is no source
# file, so BASH_SOURCE is empty. Fall back to $0 (always set, unlike
# BASH_SOURCE[0]) so `set -u` doesn't turn every piped install into an
# "unbound variable" crash before the first log line.
SCRIPT_SOURCE_INPUT="${BASH_SOURCE[0]:-$0}"
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_SOURCE_INPUT")" && pwd)"
SCRIPT_SOURCE="${SCRIPT_DIR}/$(basename "$SCRIPT_SOURCE_INPUT")"
REPO="${CAM_INSTALL_REPO:-jcyLite/cam-releases}"
# An explicit repository retains the legacy GitHub source unless a base is set.
RELEASE_BASE_URL="${CAM_INSTALL_RELEASE_BASE_URL:-${CAM_RELEASE_BASE_URL:-}}"
if [ -z "$RELEASE_BASE_URL" ] && [ -z "${CAM_INSTALL_REPO:-}" ]; then
  RELEASE_BASE_URL="https://aperioai.top/releases"
fi
RELEASE_BASE_URL="${RELEASE_BASE_URL%/}"
RELEASE="${CAM_INSTALL_RELEASE:-latest}"
RELEASE_SCAN_LIMIT="${CAM_INSTALL_RELEASE_SCAN_LIMIT:-30}"
INSTALL_SERVICES="${CAM_INSTALL_SERVICES:-}"
INSTALL_BRIDGE_DEPS="${CAM_INSTALL_BRIDGE_DEPS:-1}"
KEEP_TMP="${CAM_INSTALL_KEEP_TMP:-0}"
CURL_RETRIES="${CAM_INSTALL_CURL_RETRIES:-50}"
CURL_BROWSER_RETRIES="${CAM_INSTALL_CURL_BROWSER_RETRIES:-3}"
CURL_RETRY_DELAY="${CAM_INSTALL_CURL_RETRY_DELAY:-3}"
CURL_CONNECT_TIMEOUT="${CAM_INSTALL_CURL_CONNECT_TIMEOUT:-20}"
CURL_HTTP_VERSION="${CAM_INSTALL_CURL_HTTP_VERSION:---http1.1}"
CURL_MAX_TIME="${CAM_INSTALL_CURL_MAX_TIME:-120}"
CURL_SMALL_RETRIES="${CAM_INSTALL_CURL_SMALL_RETRIES:-2}"
CURL_SMALL_MAX_TIME="${CAM_INSTALL_CURL_SMALL_MAX_TIME:-30}"
CURL_SPEED_TIME="${CAM_INSTALL_CURL_SPEED_TIME:-60}"
CURL_SPEED_LIMIT="${CAM_INSTALL_CURL_SPEED_LIMIT:-1024}"
CAM_INSTALL_LOCALE="${CAM_INSTALL_LOCALE:-en_US.UTF-8}"
# Linux packages are built on ubuntu-22.04 (.github/workflows/release-all.yml).
# verify-local-release-package.mjs fails the release when bin/cam needs a newer
# glibc than this, so hosts below it can be refused before the download.
LINUX_MIN_GLIBC="2.34"
# The caller's PATH, before this script prepends ~/.local/bin to it.
USER_PATH="$PATH"
REMOTE_INSTALL_TMP=""

# Public release workflows replace this marker with the exact canonical lock
# library so the standalone installer can lock before its first network call.
# CAM_LOCAL_DEPLOY_LOCK_EMBED_BEGIN
# CAM_LOCAL_DEPLOY_LOCK_SHA256=5cbe33684e5c1d8c47156897dbcccbbf4106fd72f095c2c9ed7867ac9edd23c3
#!/usr/bin/env bash
# Machine-wide CAM local deployment lock.
#
# Defaults:
#   path:            ~/.cam/locks/local-deploy.lock
#   timeout:         1800 seconds (deployment fails after this bounded wait)
#   status interval: 10 seconds (holder PID, source, and held duration)
#   poll interval:   1 second
#
# Tests may override these values with CAM_LOCAL_DEPLOY_LOCK_DIR,
# CAM_LOCAL_DEPLOY_LOCK_TIMEOUT_SEC, CAM_LOCAL_DEPLOY_LOCK_STATUS_INTERVAL_SEC,
# CAM_LOCAL_DEPLOY_LOCK_POLL_INTERVAL_SEC, and
# CAM_LOCAL_DEPLOY_LOCK_INIT_GRACE_SEC. All interval values are integer seconds.
#
# The fixed path is a permanent Lamport bakery queue. Each contender publishes
# a fully initialized, never-reused claim directory with an atomic rename, then
# chooses a ticket. Dead claims are ignored rather than deleting a shared lock
# name, so stale takeover has no check/delete window and survives SIGKILL.

# Child installers inherit the claim token so they can enter reentrantly, but
# sourcing this library resets process-local release authority.
CAM_LOCAL_DEPLOY_LOCK_OWNS=0
CAM_LOCAL_DEPLOY_LOCK_HELD=0

cam_local_deploy_lock_log() {
  printf '[cam-deploy-lock] %s\n' "$*" >&2
}

cam_local_deploy_lock_error() {
  printf '[cam-deploy-lock] error: %s\n' "$*" >&2
}

cam_local_deploy_lock_positive_integer() {
  case "$2" in
    ''|*[!0-9]*|0)
      cam_local_deploy_lock_error "$1 must be a positive integer, got: $2"
      return 1
      ;;
  esac
}

cam_local_deploy_lock_nonnegative_integer() {
  case "$2" in
    ''|*[!0-9]*)
      cam_local_deploy_lock_error "$1 must be a non-negative integer, got: $2"
      return 1
      ;;
  esac
}

cam_local_deploy_lock_process_start() {
  LC_ALL=C ps -p "$1" -o lstart= 2>/dev/null |
    awk '{$1=$1; print; exit}'
}

cam_local_deploy_lock_path_mtime() {
  if stat -f %m "$1" >/dev/null 2>&1; then
    stat -f %m "$1"
  else
    stat -c %Y "$1" 2>/dev/null
  fi
}

cam_local_deploy_lock_dir_identity() {
  ls -di "$1" 2>/dev/null | awk '{print $1; exit}'
}

cam_local_deploy_lock_claim_identity_matches() {
  local claim_dir="$1"
  local expected_identity="$2"
  local current_identity
  current_identity="$(cam_local_deploy_lock_dir_identity "$claim_dir" || true)"
  [ -n "$expected_identity" ] && [ "$current_identity" = "$expected_identity" ]
}

cam_local_deploy_lock_owner_field() {
  local field="$1"
  local claim_dir="$2"
  local owner_file="${claim_dir}/owner"
  [ -f "$owner_file" ] || return 1
  awk -v prefix="${field}=" '
    index($0, prefix) == 1 {
      print substr($0, length(prefix) + 1)
      exit
    }
  ' "$owner_file"
}

cam_local_deploy_lock_ready_ticket() {
  local claim_dir="$1"
  local ticket
  [ -f "$claim_dir/ready" ] || return 1
  ticket="$(awk 'NR == 1 { print; exit }' "$claim_dir/ready")"
  case "$ticket" in
    ''|*[!0-9]*|0) return 1 ;;
  esac
  while [ "${#ticket}" -gt 1 ] && [ "${ticket#0}" != "$ticket" ]; do
    ticket="${ticket#0}"
  done
  if [ "${#ticket}" -gt 10 ] ||
    { [ "${#ticket}" -eq 10 ] && [ "$ticket" \> "2147483647" ]; }
  then
    return 1
  fi
  printf '%s\n' "$ticket"
}

cam_local_deploy_lock_held_field() {
  local field="$1"
  local claim_dir="$2"
  local held_file="${claim_dir}/held"
  [ -f "$held_file" ] || return 1
  awk -v prefix="${field}=" '
    index($0, prefix) == 1 {
      print substr($0, length(prefix) + 1)
      exit
    }
  ' "$held_file"
}

cam_local_deploy_lock_claim_status() {
  local claim_dir="$1"
  local now="$2"
  local grace="$3"
  local owner_file="${claim_dir}/owner"
  local mtime age pid recorded_start current_start token acquired_epoch

  if [ ! -f "$owner_file" ]; then
    mtime="$(cam_local_deploy_lock_path_mtime "$claim_dir" || true)"
    if [ -n "$mtime" ]; then
      age=$((now - mtime))
      if [ "$age" -le "$grace" ]; then
        printf 'initializing\n'
        return 0
      fi
    fi
    printf 'stale:owner metadata is missing\n'
    return 0
  fi

  pid="$(cam_local_deploy_lock_owner_field pid "$claim_dir" || true)"
  recorded_start="$(cam_local_deploy_lock_owner_field process_start "$claim_dir" || true)"
  token="$(cam_local_deploy_lock_owner_field token "$claim_dir" || true)"
  acquired_epoch="$(cam_local_deploy_lock_owner_field acquired_epoch "$claim_dir" || true)"
  case "$pid" in
    ''|*[!0-9]*) pid="" ;;
  esac
  case "$acquired_epoch" in
    ''|*[!0-9]*) acquired_epoch="" ;;
  esac

  if [ -z "$pid" ] || [ -z "$recorded_start" ] || [ -z "$token" ] || [ -z "$acquired_epoch" ]; then
    mtime="$(cam_local_deploy_lock_path_mtime "$owner_file" || true)"
    if [ -n "$mtime" ]; then
      age=$((now - mtime))
      if [ "$age" -le "$grace" ]; then
        printf 'initializing\n'
        return 0
      fi
    fi
    printf 'stale:owner metadata is incomplete\n'
    return 0
  fi

  current_start="$(cam_local_deploy_lock_process_start "$pid" || true)"
  if [ -z "$current_start" ]; then
    if kill -0 "$pid" 2>/dev/null; then
      printf 'unknown:could not verify process start for live holder pid %s\n' "$pid"
      return 0
    fi
    printf 'stale:holder pid %s is not running\n' "$pid"
    return 0
  fi
  if [ "$current_start" != "$recorded_start" ]; then
    printf 'stale:holder pid %s process start changed (PID was reused)\n' "$pid"
    return 0
  fi

  printf 'live\n'
}

cam_local_deploy_lock_prepare_claim() {
  local source_path="$1"
  local claims_dir="$2"
  local attempt token temp_claim claim_dir claim_identity safe_source
  local owner_pid process_start acquired_epoch acquired_at

  owner_pid="$$"
  process_start="$(cam_local_deploy_lock_process_start "$owner_pid" || true)"
  if [ -z "$process_start" ]; then
    cam_local_deploy_lock_error "could not read process start time for holder pid ${owner_pid}"
    return 1
  fi
  acquired_epoch="$(date +%s)"
  acquired_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  safe_source="$(printf '%s' "$source_path" | tr '\r\n' '  ')"

  attempt=0
  while :; do
    token="${owner_pid}-${acquired_epoch}-${RANDOM:-0}-${PPID:-0}-${attempt}"
    temp_claim="${CAM_LOCAL_DEPLOY_LOCK_DIR}/.claim.${token}.preparing"
    if mkdir "$temp_claim" 2>/dev/null; then
      break
    fi
    attempt=$((attempt + 1))
    if [ "$attempt" -ge 100 ]; then
      cam_local_deploy_lock_error "could not create a unique local deploy claim"
      return 1
    fi
  done

  {
    printf 'pid=%s\n' "$owner_pid"
    printf 'process_start=%s\n' "$process_start"
    printf 'acquired_epoch=%s\n' "$acquired_epoch"
    printf 'acquired_at=%s\n' "$acquired_at"
    printf 'token=%s\n' "$token"
    printf 'source=%s\n' "$safe_source"
  } > "$temp_claim/owner"

  claim_dir="${claims_dir}/${token}"
  if [ -e "$claim_dir" ] || ! mv "$temp_claim" "$claim_dir"; then
    rm -rf "$temp_claim" 2>/dev/null || true
    cam_local_deploy_lock_error "could not publish local deploy claim ${claim_dir}"
    return 1
  fi
  claim_identity="$(cam_local_deploy_lock_dir_identity "$claim_dir" || true)"
  if [ -z "$claim_identity" ]; then
    cam_local_deploy_lock_error "could not identify published local deploy claim ${claim_dir}"
    return 1
  fi

  CAM_LOCAL_DEPLOY_LOCK_OWNER_PID="$owner_pid"
  CAM_LOCAL_DEPLOY_LOCK_PROCESS_START="$process_start"
  CAM_LOCAL_DEPLOY_LOCK_ACQUIRED_EPOCH="$acquired_epoch"
  CAM_LOCAL_DEPLOY_LOCK_ACQUIRED_AT="$acquired_at"
  CAM_LOCAL_DEPLOY_LOCK_TOKEN="$token"
  CAM_LOCAL_DEPLOY_LOCK_SOURCE="$source_path"
  CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR="$claim_dir"
  CAM_LOCAL_DEPLOY_LOCK_CLAIM_IDENTITY="$claim_identity"
  CAM_LOCAL_DEPLOY_LOCK_OWNS=1
  export CAM_LOCAL_DEPLOY_LOCK_OWNER_PID CAM_LOCAL_DEPLOY_LOCK_PROCESS_START
  export CAM_LOCAL_DEPLOY_LOCK_ACQUIRED_EPOCH CAM_LOCAL_DEPLOY_LOCK_ACQUIRED_AT
  export CAM_LOCAL_DEPLOY_LOCK_TOKEN CAM_LOCAL_DEPLOY_LOCK_SOURCE
  export CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR
}

cam_local_deploy_lock_publish_ticket() {
  local claims_dir="$1"
  local init_grace="$2"
  local claim status other_ticket max_ticket ticket ready_tmp now

  max_ticket=0
  now="$(date +%s)"
  for claim in "$claims_dir"/*; do
    [ -d "$claim" ] || continue
    status="$(cam_local_deploy_lock_claim_status "$claim" "$now" "$init_grace")"
    case "$status" in
      live|unknown:*) ;;
      *) continue ;;
    esac
    other_ticket="$(cam_local_deploy_lock_ready_ticket "$claim" || true)"
    [ -n "$other_ticket" ] || continue
    if [ "$other_ticket" -gt "$max_ticket" ]; then
      max_ticket="$other_ticket"
    fi
  done
  if [ "$max_ticket" -ge 2147483647 ]; then
    cam_local_deploy_lock_error "live local deploy ticket reached the supported maximum"
    return 1
  fi
  ticket=$((max_ticket + 1))
  ready_tmp="${CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR}/ready.tmp.$$"
  printf '%s\n' "$ticket" > "$ready_tmp"
  if ! cam_local_deploy_lock_claim_identity_matches "$CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR" "$CAM_LOCAL_DEPLOY_LOCK_CLAIM_IDENTITY"; then
    cam_local_deploy_lock_error "lost local deploy claim before ticket publication"
    return 1
  fi
  mv "$ready_tmp" "${CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR}/ready"
  if ! cam_local_deploy_lock_claim_identity_matches "$CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR" "$CAM_LOCAL_DEPLOY_LOCK_CLAIM_IDENTITY" ||
    [ "$(cam_local_deploy_lock_ready_ticket "$CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR" || true)" != "$ticket" ]
  then
    cam_local_deploy_lock_error "lost local deploy claim while publishing ticket"
    return 1
  fi
  CAM_LOCAL_DEPLOY_LOCK_TICKET="$ticket"
  export CAM_LOCAL_DEPLOY_LOCK_TICKET
}

cam_local_deploy_lock_find_blocker() {
  local claims_dir="$1"
  local own_ticket="$2"
  local own_token="$3"
  local now="$4"
  local grace="$5"
  local claim status other_ticket other_token
  local choosing_claim best_claim best_ticket best_token

  choosing_claim=""
  best_claim=""
  best_ticket=""
  best_token=""
  for claim in "$claims_dir"/*; do
    [ -d "$claim" ] || continue
    [ "$claim" != "$CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR" ] || continue
    status="$(cam_local_deploy_lock_claim_status "$claim" "$now" "$grace")"
    case "$status" in
      stale:*) continue ;;
      initializing)
        [ -n "$choosing_claim" ] || choosing_claim="$claim"
        continue
        ;;
      live|unknown:*) ;;
      *) continue ;;
    esac

    other_ticket="$(cam_local_deploy_lock_ready_ticket "$claim" || true)"
    if [ -z "$other_ticket" ]; then
      # A live choosing claim must publish its ticket before later contenders
      # can decide. A claim published after this scan will see our ready ticket.
      [ -n "$choosing_claim" ] || choosing_claim="$claim"
      continue
    fi
    other_token="$(cam_local_deploy_lock_owner_field token "$claim" || true)"
    if [ "$other_ticket" -lt "$own_ticket" ] ||
      { [ "$other_ticket" -eq "$own_ticket" ] && [ "$other_token" \< "$own_token" ]; }
    then
      if [ -z "$best_claim" ] || [ "$other_ticket" -lt "$best_ticket" ] ||
        { [ "$other_ticket" -eq "$best_ticket" ] && [ "$other_token" \< "$best_token" ]; }
      then
        best_claim="$claim"
        best_ticket="$other_ticket"
        best_token="$other_token"
      fi
    fi
  done
  if [ -n "$best_claim" ]; then
    printf '%s\n' "$best_claim"
    return 0
  fi
  if [ -n "$choosing_claim" ]; then
    printf '%s\n' "$choosing_claim"
    return 0
  fi
  return 1
}

cam_local_deploy_lock_print_holder() {
  local claim_dir="$1"
  local now="$2"
  local pid source acquired_epoch held
  pid="$(cam_local_deploy_lock_owner_field pid "$claim_dir" || true)"
  source="$(cam_local_deploy_lock_owner_field source "$claim_dir" || true)"
  acquired_epoch="$(cam_local_deploy_lock_held_field acquired_epoch "$claim_dir" || true)"
  if [ -z "$acquired_epoch" ]; then
    acquired_epoch="$(cam_local_deploy_lock_owner_field acquired_epoch "$claim_dir" || true)"
  fi
  case "$acquired_epoch" in
    ''|*[!0-9]*) held="unknown" ;;
    *)
      held=$((now - acquired_epoch))
      [ "$held" -ge 0 ] || held=0
      held="${held}s"
      ;;
  esac
  [ -n "$pid" ] || pid="unknown"
  [ -n "$source" ] || source="unknown"
  cam_local_deploy_lock_log "waiting for local deploy lock ${CAM_LOCAL_DEPLOY_LOCK_DIR}; holder pid=${pid} source=${source} held=${held}"
}

cam_local_deploy_lock_claim_valid() {
  local disk_token disk_ticket
  cam_local_deploy_lock_claim_identity_matches "$CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR" "$CAM_LOCAL_DEPLOY_LOCK_CLAIM_IDENTITY" || return 1
  disk_token="$(cam_local_deploy_lock_owner_field token "$CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR" || true)"
  disk_ticket="$(cam_local_deploy_lock_ready_ticket "$CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR" || true)"
  [ "$disk_token" = "$CAM_LOCAL_DEPLOY_LOCK_TOKEN" ] &&
    [ "$disk_ticket" = "$CAM_LOCAL_DEPLOY_LOCK_TICKET" ]
}

cam_local_deploy_lock_mark_acquired() {
  local held_tmp acquired_epoch acquired_at disk_epoch
  acquired_epoch="$(date +%s)"
  acquired_at="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
  held_tmp="${CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR}/held.tmp.$$"
  {
    printf 'acquired_epoch=%s\n' "$acquired_epoch"
    printf 'acquired_at=%s\n' "$acquired_at"
  } > "$held_tmp"
  if ! cam_local_deploy_lock_claim_valid; then
    cam_local_deploy_lock_error "lost local deploy claim before held-time publication"
    return 1
  fi
  mv "$held_tmp" "${CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR}/held"
  disk_epoch="$(cam_local_deploy_lock_held_field acquired_epoch "$CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR" || true)"
  if ! cam_local_deploy_lock_claim_valid || [ "$disk_epoch" != "$acquired_epoch" ]; then
    cam_local_deploy_lock_error "lost local deploy claim while publishing held time"
    return 1
  fi
  CAM_LOCAL_DEPLOY_LOCK_ACQUIRED_EPOCH="$acquired_epoch"
  CAM_LOCAL_DEPLOY_LOCK_ACQUIRED_AT="$acquired_at"
  export CAM_LOCAL_DEPLOY_LOCK_ACQUIRED_EPOCH CAM_LOCAL_DEPLOY_LOCK_ACQUIRED_AT
}

cam_local_deploy_lock_acquire() {
  local source_path="${1:-unknown}"
  local timeout status_interval poll_interval init_grace
  local claims_dir inherited_token inherited_claim disk_token status disk_ticket
  local wait_started next_status now elapsed blocker

  CAM_LOCAL_DEPLOY_LOCK_DIR="${CAM_LOCAL_DEPLOY_LOCK_DIR:-$HOME/.cam/locks/local-deploy.lock}"
  timeout="${CAM_LOCAL_DEPLOY_LOCK_TIMEOUT_SEC:-1800}"
  status_interval="${CAM_LOCAL_DEPLOY_LOCK_STATUS_INTERVAL_SEC:-10}"
  poll_interval="${CAM_LOCAL_DEPLOY_LOCK_POLL_INTERVAL_SEC:-1}"
  init_grace="${CAM_LOCAL_DEPLOY_LOCK_INIT_GRACE_SEC:-5}"

  cam_local_deploy_lock_positive_integer CAM_LOCAL_DEPLOY_LOCK_TIMEOUT_SEC "$timeout" || return 1
  cam_local_deploy_lock_positive_integer CAM_LOCAL_DEPLOY_LOCK_STATUS_INTERVAL_SEC "$status_interval" || return 1
  cam_local_deploy_lock_positive_integer CAM_LOCAL_DEPLOY_LOCK_POLL_INTERVAL_SEC "$poll_interval" || return 1
  cam_local_deploy_lock_nonnegative_integer CAM_LOCAL_DEPLOY_LOCK_INIT_GRACE_SEC "$init_grace" || return 1

  claims_dir="${CAM_LOCAL_DEPLOY_LOCK_DIR}/claims"
  export CAM_LOCAL_DEPLOY_LOCK_DIR
  inherited_token="${CAM_LOCAL_DEPLOY_LOCK_TOKEN:-}"
  inherited_claim="${CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR:-}"
  case "$inherited_claim" in
    "$claims_dir"/*)
      disk_token="$(cam_local_deploy_lock_owner_field token "$inherited_claim" || true)"
      disk_ticket="$(cam_local_deploy_lock_ready_ticket "$inherited_claim" || true)"
      now="$(date +%s)"
      status="$(cam_local_deploy_lock_claim_status "$inherited_claim" "$now" "$init_grace")"
      if [ -n "$inherited_token" ] && [ "$disk_token" = "$inherited_token" ] &&
        [ -n "$disk_ticket" ] &&
        { [ "$status" = "live" ] || [ "${status#unknown:}" != "$status" ]; }
      then
        CAM_LOCAL_DEPLOY_LOCK_HELD=1
        CAM_LOCAL_DEPLOY_LOCK_OWNS=0
        cam_local_deploy_lock_log "using inherited local deploy lock ${CAM_LOCAL_DEPLOY_LOCK_DIR} for ${source_path}"
        return 0
      fi
      ;;
  esac

  mkdir -p "$claims_dir"
  wait_started="$(date +%s)"
  next_status="$wait_started"
  if ! cam_local_deploy_lock_prepare_claim "$source_path" "$claims_dir"; then
    return 1
  fi
  if ! cam_local_deploy_lock_publish_ticket "$claims_dir" "$init_grace"; then
    cam_local_deploy_lock_release
    return 1
  fi

  while :; do
    now="$(date +%s)"
    blocker="$(cam_local_deploy_lock_find_blocker "$claims_dir" "$CAM_LOCAL_DEPLOY_LOCK_TICKET" "$CAM_LOCAL_DEPLOY_LOCK_TOKEN" "$now" "$init_grace" || true)"
    if [ -z "$blocker" ]; then
      if ! cam_local_deploy_lock_claim_valid; then
        cam_local_deploy_lock_error "lost local deploy claim before acquisition completed"
        cam_local_deploy_lock_release
        return 1
      fi
      if ! cam_local_deploy_lock_mark_acquired; then
        cam_local_deploy_lock_release
        return 1
      fi
      CAM_LOCAL_DEPLOY_LOCK_HELD=1
      cam_local_deploy_lock_log "acquired local deploy lock ${CAM_LOCAL_DEPLOY_LOCK_DIR}; pid=${CAM_LOCAL_DEPLOY_LOCK_OWNER_PID} source=${CAM_LOCAL_DEPLOY_LOCK_SOURCE}"
      return 0
    fi

    elapsed=$((now - wait_started))
    if [ "$elapsed" -ge "$timeout" ]; then
      cam_local_deploy_lock_error "timed out after ${timeout}s waiting for local deploy lock ${CAM_LOCAL_DEPLOY_LOCK_DIR}"
      cam_local_deploy_lock_print_holder "$blocker" "$now"
      cam_local_deploy_lock_release
      return 1
    fi
    if [ "$now" -ge "$next_status" ]; then
      cam_local_deploy_lock_print_holder "$blocker" "$now"
      next_status=$((now + status_interval))
    fi
    sleep "$poll_interval"
  done
}

cam_local_deploy_lock_release() {
  local disk_token claim_dir claims_dir
  if [ "${CAM_LOCAL_DEPLOY_LOCK_OWNS:-0}" != "1" ]; then
    return 0
  fi

  claim_dir="${CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR:-}"
  claims_dir="${CAM_LOCAL_DEPLOY_LOCK_DIR}/claims"
  case "$claim_dir" in
    "$claims_dir"/*) ;;
    *)
      cam_local_deploy_lock_log "not releasing local deploy claim with an unexpected path: ${claim_dir:-unknown}"
      CAM_LOCAL_DEPLOY_LOCK_OWNS=0
      CAM_LOCAL_DEPLOY_LOCK_HELD=0
      return 0
      ;;
  esac
  disk_token="$(cam_local_deploy_lock_owner_field token "$claim_dir" || true)"
  if [ -z "${CAM_LOCAL_DEPLOY_LOCK_TOKEN:-}" ] || [ "$disk_token" != "$CAM_LOCAL_DEPLOY_LOCK_TOKEN" ]; then
    cam_local_deploy_lock_log "not releasing ${claim_dir}: owner token changed"
  elif cam_local_deploy_lock_claim_identity_matches "$claim_dir" "${CAM_LOCAL_DEPLOY_LOCK_CLAIM_IDENTITY:-}"; then
    rm -rf "$claim_dir" 2>/dev/null || true
    cam_local_deploy_lock_log "released local deploy lock ${CAM_LOCAL_DEPLOY_LOCK_DIR}"
  fi
  CAM_LOCAL_DEPLOY_LOCK_OWNS=0
  CAM_LOCAL_DEPLOY_LOCK_HELD=0
  unset CAM_LOCAL_DEPLOY_LOCK_TOKEN CAM_LOCAL_DEPLOY_LOCK_CLAIM_DIR
  unset CAM_LOCAL_DEPLOY_LOCK_CLAIM_IDENTITY CAM_LOCAL_DEPLOY_LOCK_TICKET
}

cam_local_deploy_lock_on_exit() {
  local status="$?"
  trap - EXIT
  cam_local_deploy_lock_release
  exit "$status"
}

cam_local_deploy_lock_on_int() {
  trap - INT
  exit 130
}

cam_local_deploy_lock_on_term() {
  trap - TERM
  exit 143
}

cam_local_deploy_lock_install_traps() {
  trap 'cam_local_deploy_lock_on_exit' EXIT
  trap 'cam_local_deploy_lock_on_int' INT
  trap 'cam_local_deploy_lock_on_term' TERM
}
# CAM_LOCAL_DEPLOY_LOCK_EMBED_END
#!/usr/bin/env bash
# Preserve user-owned programs; all newly created aliases are relative.
cam_aperio_alias_is_owned() {
  local bin_dir="$1" target target_dir bin_real
  [ -L "$bin_dir/aperio" ] || return 1
  target="$(readlink "$bin_dir/aperio")" || return 1
  case "$target" in /*) ;; *) target="$bin_dir/$target" ;; esac
  [ "$(basename "$target")" = cam ] || return 1
  target_dir="$(cd "$(dirname "$target")" 2>/dev/null && pwd -P)" || return 1
  bin_real="$(cd "$bin_dir" 2>/dev/null && pwd -P)" || return 1
  [ "$target_dir" = "$bin_real" ]
}

cam_aperio_alias_run() {
  if declare -F run >/dev/null 2>&1; then run "$@"; else "$@"; fi
}

cam_ensure_aperio_alias() {
  local bin_dir="$1"
  if [ -e "$bin_dir/aperio" ] || [ -L "$bin_dir/aperio" ]; then
    if ! cam_aperio_alias_is_owned "$bin_dir"; then
      printf 'warning: %s/aperio is not a link to cam; skipping alias\n' "$bin_dir" >&2
    fi
    return 0
  fi
  cam_aperio_alias_run ln -s cam "$bin_dir/aperio"
}

cam_remove_aperio_alias() {
  if cam_aperio_alias_is_owned "$1"; then
    cam_aperio_alias_run rm -- "$1/aperio"
  fi
  return 0
}

# Quote an install path as data in POSIX, zsh and fish startup files.
cam_command_path_literal() {
  printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")"
}

cam_write_command_path() {
  local prefix="$1" profile="$2" block="$3" staged backup
  if { [ -e "$profile" ] || [ -L "$profile" ]; } && { [ ! -f "$profile" ] || [ ! -w "$profile" ]; }; then
    printf '%s error: cannot configure command PATH in %s; make this shell profile writable and rerun\n' "$prefix" "$profile" >&2
    return 1
  fi
  mkdir -p "$(dirname "$profile")" || return 1
  staged="$(mktemp "${TMPDIR:-/tmp}/cam-shell-path.XXXXXXXX")" || return 1
  if [ -f "$profile" ]; then
    # Replace only our complete managed block; preserve user settings and links.
    if ! awk '
      $0 == "# >>> CAM command path >>>" { if (inside || seen) exit 2; inside=1; seen=1; next }
      $0 == "# <<< CAM command path <<<" { if (!inside) exit 2; inside=0; next }
      !inside { print }
      END { if (inside) exit 2 }
    ' "$profile" > "$staged"; then
      rm -f "$staged"
      printf '%s error: incomplete CAM PATH block in %s; repair it and rerun\n' "$prefix" "$profile" >&2
      return 1
    fi
  fi
  printf '%s\n' "$block" >> "$staged"
  if [ -f "$profile" ] && cmp -s "$profile" "$staged"; then
    rm -f "$staged"
    return 0
  fi
  backup=''
  if [ -f "$profile" ]; then
    backup="${profile}.cam-backup.$(date -u +%Y%m%dT%H%M%SZ).$$"
    if ! cp -p "$profile" "$backup"; then rm -f "$staged"; return 1; fi
  fi
  # Writing through an existing symlink retains dotfile-manager ownership.
  if ! (umask 077; cat "$staged" > "$profile"); then
    if [ -n "$backup" ]; then cat "$backup" > "$profile" || true; fi
    rm -f "$staged"
    printf '%s error: failed to save command PATH in %s\n' "$prefix" "$profile" >&2
    return 1
  fi
  rm -f "$staged"
  printf '%s configured command PATH in %s\n' "$prefix" "$profile"
}

cam_configure_command_path() {
  local prefix="$1" bin_dir="$2" search_path="$3" literal block profile path_code env_block
  case "$bin_dir" in
    /*) ;;
    *) printf '%s error: command install directory must be absolute\n' "$prefix" >&2; return 1 ;;
  esac
  literal="$(cam_command_path_literal "$bin_dir")"
  printf -v path_code 'case ":${PATH:-}:" in
  *:%s:*) ;;
  *) export PATH=%s:"${PATH:-}" ;;
esac' "$literal" "$literal"
  printf -v block '# >>> CAM command path >>>\n%s\n# <<< CAM command path <<<' "$path_code"
  case "${SHELL:-}" in
    */zsh)
      # macOS path_helper runs in /etc/zprofile. Configure login PATH after it;
      # non-login/SSH shells use .zshenv without passing paths through its eval.
      printf -v env_block '# >>> CAM command path >>>\nif [[ ! -o login ]]; then\n%s\nfi\n# <<< CAM command path <<<' "$path_code"
      cam_write_command_path "$prefix" "${ZDOTDIR:-$HOME}/.zprofile" "$block" || return 1
      cam_write_command_path "$prefix" "${ZDOTDIR:-$HOME}/.zshenv" "$env_block" || return 1
      ;;
    */bash)
      profile="$HOME/.profile"
      if [ -e "$HOME/.bash_profile" ] || [ -L "$HOME/.bash_profile" ]; then
        profile="$HOME/.bash_profile"
      elif [ -e "$HOME/.bash_login" ] || [ -L "$HOME/.bash_login" ]; then
        profile="$HOME/.bash_login"
      fi
      cam_write_command_path "$prefix" "$profile" "$block" || return 1
      cam_write_command_path "$prefix" "$HOME/.bashrc" "$block" || return 1
      ;;
    */fish)
      printf -v block '# >>> CAM command path >>>
if not contains -- %s $PATH
  set -gx PATH %s $PATH
end
# <<< CAM command path <<<' "$literal" "$literal"
      cam_write_command_path "$prefix" "${XDG_CONFIG_HOME:-$HOME/.config}/fish/conf.d/cam-path.fish" "$block" || return 1
      ;;
    *) cam_write_command_path "$prefix" "$HOME/.profile" "$block" || return 1 ;;
  esac
  cam_print_path_hint "$prefix" "$bin_dir" "$search_path"
}

# A piped child process cannot export PATH into the terminal that launched it.
cam_print_path_hint() {
  local prefix="$1" bin_dir="$2" search_path="$3" literal
  case ":${search_path}:" in
    *":${bin_dir}:"* | *":${bin_dir}/:"*) return 0 ;;
  esac
  literal="$(cam_command_path_literal "$bin_dir")"
  printf '%s PATH is configured for new terminals. Open a new terminal to run cam or aperio.\n' "$prefix"
  printf '%s To use this terminal immediately, run:\n' "$prefix"
  case "${SHELL:-}" in
    */fish)
      printf '%s   set -gx PATH %s $PATH\n' "$prefix" "$literal"
      return 0
      ;;
  esac
  printf '%s   export PATH=%s:"$PATH"\n' "$prefix" "$literal"
}

#!/usr/bin/env bash
# Shared by the standalone downloader and the generated package installer.
# Dependency installation precedes CAM replacement; no credential reads or service mutations.
cam_first_run_mode() {
  INSTALL_SERVICES="${CAM_INSTALL_SERVICES:-}"
  if [ -z "$INSTALL_SERVICES" ]; then
    if [ "$(uname -s)" = Darwin ]; then INSTALL_SERVICES=1; else INSTALL_SERVICES=0; fi
  fi
  case "$INSTALL_SERVICES" in
    0|1) ;;
    *) cam_first_run_block "CAM_INSTALL_SERVICES must be 0 or 1" ;;
  esac
}

cam_first_run_block() {
  printf '[cam-install] incomplete: %s\n' "$*" >&2
  return 1
}

select_usable_node() {
  local candidate version major minor
  for candidate in \
    "$(command -v node 2>/dev/null || true)" \
    "$HOME/.volta/bin/node" /opt/homebrew/bin/node /usr/local/bin/node \
    "$HOME/.npm-global/bin/node" "$HOME/.local/bin/node"
  do
    [ -n "$candidate" ] && [ -x "$candidate" ] || continue
    version="$("$candidate" --version 2>/dev/null || true)"
    [[ "$version" =~ ^v([0-9]+)\.([0-9]+)\.([0-9]+)$ ]] || continue
    major="${BASH_REMATCH[1]}"; minor="${BASH_REMATCH[2]}"
    if [ "$major" -gt 18 ] || { [ "$major" -eq 18 ] && [ "$minor" -ge 18 ]; }; then
      printf '%s %s\n' "$candidate" "$version"
      return 0
    fi
  done
  return 1
}

cam_tmux_available() {
  command -v tmux >/dev/null 2>&1 && tmux -V >/dev/null 2>&1
}

cam_find_homebrew() {
  local candidate
  for candidate in "$(command -v brew 2>/dev/null || true)" /opt/homebrew/bin/brew /usr/local/bin/brew; do
    if [ -n "$candidate" ] && [ -x "$candidate" ]; then
      printf '%s\n' "$candidate"
      return 0
    fi
  done
  return 1
}

cam_bootstrap_homebrew() {
  local dependency="${1:-tmux}" installer result=0
  printf '[cam-install] %s needs Homebrew; installing Homebrew from its official installer\n' "$dependency"
  installer="$(mktemp "${TMPDIR:-/tmp}/cam-homebrew-install.XXXXXXXX")" || return 1
  if ! curl -fsSL --connect-timeout 20 --max-time 180 \
    https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh -o "$installer"; then
    rm -f "$installer"
    cam_first_run_block "could not download the official Homebrew installer for $dependency; check network access and retry"
    return 1
  fi
  if [ -t 1 ] && [ -r /dev/tty ]; then
    printf '[cam-install] Homebrew may ask for your macOS administrator password and installation confirmation\n'
    /bin/bash "$installer" </dev/tty || result=$?
  else
    NONINTERACTIVE=1 /bin/bash "$installer" </dev/null || result=$?
  fi
  rm -f "$installer"
  if [ "$result" -ne 0 ]; then
    cam_first_run_block "Homebrew installation failed (exit $result); resolve its reported permissions/dependencies or run its installer in a local terminal, then retry CAM"
    return 1
  fi
}

cam_prepare_homebrew() {
  local dependency="$1" prefix
  CAM_RUNTIME_BREW="$(cam_find_homebrew || true)"
  if [ -z "$CAM_RUNTIME_BREW" ]; then
    cam_bootstrap_homebrew "$dependency" || return 1
    CAM_RUNTIME_BREW="$(cam_find_homebrew || true)"
  fi
  if [ -z "$CAM_RUNTIME_BREW" ]; then
    cam_first_run_block "Homebrew finished, but brew is unavailable; check its installation and retry to install $dependency"
    return 1
  fi
  prefix="$("$CAM_RUNTIME_BREW" --prefix)" || {
    cam_first_run_block "cannot determine the Homebrew prefix for $dependency; repair Homebrew and retry"
    return 1
  }
  case "$prefix" in
    /*) export PATH="$prefix/bin:$prefix/sbin:$PATH" ;;
    *) cam_first_run_block "Homebrew returned an invalid prefix for $dependency"; return 1 ;;
  esac
}

ensure_node_runtime() {
  local mode="${CAM_INSTALL_RUNTIME_DEPS:-1}" runtime result=0
  case "$mode" in
    0|1) ;;
    *) cam_first_run_block "CAM_INSTALL_RUNTIME_DEPS must be 0 or 1"; return 1 ;;
  esac
  if runtime="$(select_usable_node)"; then
    export PATH="$(dirname "${runtime% *}"):$PATH"
    return 0
  fi
  if [ "$mode" = 0 ]; then
    cam_first_run_block "Node.js >=18.18 is required, but automatic installation is disabled by CAM_INSTALL_RUNTIME_DEPS=0"
    return 1
  fi
  if [ "$(uname -s)" != Darwin ]; then
    cam_first_run_block "Node.js >=18.18 is required for the complete install; install Node.js LTS from https://nodejs.org, then rerun the installer"
    return 1
  fi
  cam_prepare_homebrew Node.js || return 1
  # An existing keg may become visible after adding Homebrew's prefix.
  if ! select_usable_node >/dev/null; then
    printf '[cam-install] Node.js missing or older than 18.18; installing with Homebrew\n'
    "$CAM_RUNTIME_BREW" install node || result=$?
    if [ "$result" -ne 0 ]; then
      cam_first_run_block "failed to install Node.js with Homebrew (exit $result); resolve the package manager error and retry CAM"
      return 1
    fi
  fi
  hash -r
  runtime="$(select_usable_node)" || {
    cam_first_run_block "Node.js >=18.18 is still unavailable after Homebrew installation; check Homebrew and PATH, then retry"
    return 1
  }
  export PATH="$(dirname "${runtime% *}"):$PATH"
  printf '[cam-install] Node.js ready and verified: %s\n' "$runtime"
}

cam_dependency_command() {
  if [ "$(id -u)" = 0 ]; then
    "$@"
  elif command -v sudo >/dev/null 2>&1; then
    if [ -t 1 ] && [ -r /dev/tty ]; then
      sudo "$@" </dev/tty
    else
      sudo -n "$@" </dev/null
    fi
  else
    cam_first_run_block "installing tmux needs root or sudo; install it with your system package manager and retry"
    return 1
  fi
}

ensure_tmux_runtime() {
  local mode="${CAM_INSTALL_RUNTIME_DEPS:-1}" result=0
  case "$mode" in
    0|1) ;;
    *) cam_first_run_block "CAM_INSTALL_RUNTIME_DEPS must be 0 or 1"; return 1 ;;
  esac
  if cam_tmux_available; then return 0; fi
  if [ "$mode" = 0 ]; then
    cam_first_run_block "tmux is required, but automatic installation is disabled by CAM_INSTALL_RUNTIME_DEPS=0"
    return 1
  fi

  case "$(uname -s)" in
    Darwin)
      cam_prepare_homebrew tmux || return 1
      if cam_tmux_available; then return 0; fi
      printf '[cam-install] tmux not found or unusable; installing with Homebrew\n'
      "$CAM_RUNTIME_BREW" install tmux || result=$?
      ;;
    Linux)
      printf '[cam-install] tmux not found or unusable; installing with the system package manager\n'
      if command -v apt-get >/dev/null 2>&1; then
        { cam_dependency_command apt-get update && cam_dependency_command apt-get install -y tmux; } || result=$?
      elif command -v dnf >/dev/null 2>&1; then
        cam_dependency_command dnf install -y tmux || result=$?
      elif command -v yum >/dev/null 2>&1; then
        cam_dependency_command yum install -y tmux || result=$?
      elif command -v pacman >/dev/null 2>&1; then
        cam_dependency_command pacman -S --needed --noconfirm tmux || result=$?
      elif command -v apk >/dev/null 2>&1; then
        cam_dependency_command apk add tmux || result=$?
      else
        cam_first_run_block "tmux is required; no supported package manager found (apt-get, dnf, yum, pacman, apk)"
        return 1
      fi
      ;;
    *) cam_first_run_block "tmux is required; install it with your system package manager and retry"; return 1 ;;
  esac
  if [ "$result" -ne 0 ]; then
    cam_first_run_block "failed to install tmux (exit $result); resolve the package manager error and retry CAM"
    return 1
  fi
  hash -r
  if ! cam_tmux_available; then
    cam_first_run_block "tmux is still unavailable or cannot run after dependency installation; check the package manager and PATH, then retry"
    return 1
  fi
  printf '[cam-install] tmux installed and verified\n'
}

cam_first_run_port_preflight() {
  local port="${1:-3456}"
  local pids pid cmd managed
  case "$port" in ''|*[!0-9]*) cam_first_run_block "invalid dashboard port; use 1..65535"; return 1 ;; esac
  [ "$port" -ge 1 ] && [ "$port" -le 65535 ] || { cam_first_run_block "invalid dashboard port; use 1..65535"; return 1; }
  command -v lsof >/dev/null 2>&1 || { cam_first_run_block "cannot inspect port $port; install lsof, then retry"; return 1; }
  pids="$(lsof -nP -iTCP:"$port" -sTCP:LISTEN -t 2>/dev/null || true)"
  managed="$(launchctl print "gui/$(id -u)/com.cam.mac-bridge" 2>/dev/null | sed -n 's/^[[:space:]]*pid = \([0-9][0-9]*\).*/\1/p' || true)"
  for pid in $pids; do
    [ "$pid" != "$managed" ] || continue
    cmd="$(ps -p "$pid" -o command= 2>/dev/null || true)"
    case "$cmd" in
      *"${CAM_INSTALL_DIR:-$HOME/.local/share/code-agent-monitor}/cam-bridge/mac-bridge.js"*|*"$HOME/.local/bin/cam watch-daemon"*)
        if [ "${CAM_INSTALL_FIX_DASHBOARD_PORT:-1}" != 1 ]; then
          cam_first_run_block "stale Aperio listener on port $port; inspect it, then retry with CAM_INSTALL_FIX_DASHBOARD_PORT=1"
          return 1
        fi
        ;;
      *)
        cam_first_run_block "port $port is occupied by an unrelated or unknown process (pid=$pid); nothing stopped. Inspect with lsof -nP -iTCP:$port -sTCP:LISTEN, resolve the conflict, then retry"
        return 1
        ;;
    esac
  done
}

cam_first_run_preflight() {
  [ "$INSTALL_SERVICES" = 1 ] || return 0
  local runtime
  if [ "$(uname -s)" = Darwin ]; then
    launchctl print "gui/$(id -u)" >/dev/null 2>&1 || {
      cam_first_run_block "waiting for a macOS user session: complete macOS setup and log in locally as this user, then retry (SSH alone does not create a GUI launchd session)"
      return 1
    }
    # Generated launchd services use 3456. Keep the legacy extra-port check
    # without letting that knob bypass protection of the actual service port.
    cam_first_run_port_preflight 3456 || return 1
    if [ -n "${CAM_DASHBOARD_PORT:-}" ] && [ "$CAM_DASHBOARD_PORT" != 3456 ]; then
      cam_first_run_port_preflight "$CAM_DASHBOARD_PORT" || return 1
    fi
  fi
  ensure_node_runtime || return 1
  runtime="$(select_usable_node)" || return 1
  ensure_tmux_runtime || return 1
  printf '[cam-install] complete-install preflight passed (Node: %s; tmux available)\n' "$runtime"
}

cam_first_run_prepare_access() {
  [ "$INSTALL_SERVICES" = 1 ] && [ "$(uname -s)" = Darwin ] || return 0
  local mode="${CAM_INSTALL_ALLOW_REMOTE:-default}" runtime
  case "$mode" in
    default|0|1) ;;
    *) cam_first_run_block "CAM_INSTALL_ALLOW_REMOTE must be 0 or 1"; return 1 ;;
  esac
  runtime="$(select_usable_node)" || return 1
  if ! "${runtime% *}" - "$HOME/.config/code-agent-monitor/config.json" "$mode" <<'NODE'
const fs = require('node:fs');
const path = require('node:path');
const { randomUUID } = require('node:crypto');
const [file, mode] = process.argv.slice(2);
let staged;
try {
  const exists = fs.existsSync(file);
  const config = exists ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
  if (!config || typeof config !== 'object' || Array.isArray(config)) throw new Error('config must be an object');
  if (config.dashboard === undefined) config.dashboard = {};
  if (!config.dashboard || typeof config.dashboard !== 'object' || Array.isArray(config.dashboard)) throw new Error('dashboard must be an object');
  const current = config.dashboard.allow_remote;
  if (current !== undefined && typeof current !== 'boolean') throw new Error('dashboard.allow_remote must be boolean');
  const next = mode === 'default' ? (current ?? true) : mode === '1';
  if (current === next) process.exit(0);
  config.dashboard.allow_remote = next;
  // Preserve user-owned symlinks, unrelated settings and private file modes.
  if (!exists && fs.lstatSync(path.dirname(file), { throwIfNoEntry: false }) === undefined) fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
  if (!exists && fs.lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink()) throw new Error('config symlink target is missing');
  const target = exists ? fs.realpathSync(file) : file;
  staged = path.join(path.dirname(target), `.cam-access-${randomUUID()}`);
  fs.writeFileSync(staged, JSON.stringify(config, null, 2) + '\n', { flag: 'wx', mode: exists ? fs.statSync(target).mode & 0o777 : 0o600 });
  fs.renameSync(staged, target);
  staged = undefined;
  console.log(`[cam-install] Dashboard LAN access ${next ? 'enabled (access password required)' : 'disabled (loopback only)'}`);
} catch {
  console.error('[cam-install] incomplete: cannot save Dashboard access settings; check config.json syntax, dashboard.allow_remote and file permissions, then retry');
  process.exitCode = 1;
} finally {
  if (staged) try { fs.unlinkSync(staged); } catch {}
}
NODE
  then
    return 1
  fi
}

cam_first_run_access_hint() {
  if [ "${1:-current}" = legacy ]; then
    printf '[cam-install] access/readiness: rerun this installer to check the local service and Dashboard\n'
    printf '[cam-install] Aperio console access password (not a system or provider password): on the service host, as the installing user, explicitly run:\n'
    printf '  cat "$HOME/.config/code-agent-monitor/local-dashboard-token"\n'
    printf '[cam-install] if the private password file is missing, empty or unreadable, check the installing user and service startup before retrying; do not substitute another password\n'
  else
    printf '[cam-install] access and readiness: cam dashboard; password: cam dashboard --show-password (run as the installing user on the service host)\n'
  fi
}

# Historical releases have no `cam dashboard`. Keep their checks in the
# downloader (also embedded in the standalone script), independent of the CLI.
# Match src/service/dashboard_probe.rs: loopback only, no credentials/proxies or
# redirects, 3-second total request deadlines and bounded response bodies.
cam_first_run_legacy_probe() {
  local runtime
  runtime="$(select_usable_node)" || { cam_first_run_block "Node.js >=18.18 is required to verify the service; install Node.js LTS and rerun this installer"; return 1; }
  "${runtime% *}" - <<'NODE'
const http = require('node:http');
const port = Number(process.env.LOCAL_DASHBOARD_PORT || 3456);
const base = `http://127.0.0.1:${port}`;
const next = 'check the local service logs, resolve the problem and rerun this installer';

function body(path, label) {
  return new Promise((resolve, reject) => {
    const fail = (message) => {
      clearTimeout(timer);
      request.destroy();
      reject(new Error(`${label}: ${message}`));
    };
    const request = http.get(`${base}${path}`, { agent: false }, (response) => {
      const status = response.statusCode;
      if (status === 401 || status === 403) {
        fail(`authentication rejected (HTTP ${status}); check service/proxy access rules without disabling console authentication, then rerun this installer`);
        return;
      }
      if (status !== 200) {
        fail(`HTTP ${status}; ${label === 'Dashboard' ? 'Aperio Dashboard page unavailable; rerun this installer to repair static assets' : next}`);
        return;
      }
      let size = 0;
      const chunks = [];
      response.on('data', (chunk) => {
        size += chunk.length;
        if (size > 4 * 1024 * 1024) {
          fail('response too large to verify Aperio; inspect the port listener and rerun this installer');
          return;
        }
        chunks.push(chunk);
      });
      response.on('error', () => fail(`network response failed; ${next}`));
      response.on('end', () => {
        clearTimeout(timer);
        try {
          resolve({ type: (response.headers['content-type'] || '').toLowerCase(),
            text: new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)) });
        } catch {
          fail(`invalid response encoding; ${next}`);
        }
      });
    });
    const timer = setTimeout(() => fail(`network timeout (3s); ${next}`), 3000);
    request.on('error', (error) => fail(error.code === 'ECONNREFUSED'
      ? `cannot connect to the local service; ${next}` : `network response failed; ${next}`));
  });
}

(async () => {
  if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('invalid dashboard port; use 1..65535');
  console.log(`[cam-install] local URL: ${base}/static/dashboard-new/`);
  const healthBody = await body('/health', '/health');
  let health;
  try { health = JSON.parse(healthBody.text); } catch { /* Classified below; never log response bodies. */ }
  if (health?.service !== 'cam-local-dashboard') {
    throw new Error('/health: non-Aperio response; inspect the port listener, do not stop unknown processes, then rerun this installer');
  }
  if (health.ok !== true || health.status !== 'ok') throw new Error(`/health: Aperio health is unhealthy or degraded; ${next}`);
  const page = await body('/static/dashboard-new/', 'Dashboard');
  if (!page.type.startsWith('text/html') || !page.text.includes('<title>Aperio</title>') || !page.text.includes('/_next/static/')) {
    throw new Error('Dashboard: complete Aperio Dashboard page not found; rerun this installer to repair static assets');
  }
  console.log('[cam-install] service ready: Aperio identity, health and Dashboard page verified');
})().catch((error) => {
  console.error(`[cam-install] incomplete: ${error.message}`);
  process.exitCode = 1;
});
NODE
}

cam_first_run_finish() {
  local cam_binary="$1" access_mode="${2:-current}"
  if [ "$INSTALL_SERVICES" = 0 ]; then
    printf '[cam-install] CLI-only installation complete; dashboard/service readiness was not checked. Next: prepare Node and tmux, then rerun this installer with CAM_INSTALL_SERVICES=1\n'
    return 0
  fi
  if [ "$access_mode" = legacy ]; then
    cam_first_run_legacy_probe || return 1
  elif ! "$cam_binary" dashboard; then
    cam_first_run_block "service readiness check failed; inspect cam service logs --target mac-bridge, fix the reported problem, then rerun the installer or cam dashboard"
    return 1
  fi
  printf '[cam-install] complete installation ready on this host; remote connections require the console access password (network reachability is not verified)\n'
  cam_first_run_access_hint "$access_mode"
  if [ -n "${SSH_CONNECTION:-}${SSH_TTY:-}" ]; then
    printf '[cam-install] SSH session: use this host\047s LAN/Tailscale address when remote access is enabled; no browser was opened\n'
  fi
}


load_first_run_library() {
  if ! declare -F cam_first_run_mode >/dev/null 2>&1; then
    source "$SCRIPT_DIR/lib/first-run.sh"
  fi
}

load_aperio_alias_library() {
  if ! declare -F cam_ensure_aperio_alias >/dev/null 2>&1; then
    source "$SCRIPT_DIR/lib/aperio-alias.sh"
  fi
}

load_local_deploy_lock_library() {
  local candidate
  if declare -F cam_local_deploy_lock_acquire >/dev/null 2>&1; then
    return 0
  fi

  for candidate in \
    "${CAM_LOCAL_DEPLOY_LOCK_LIB:-}" \
    "$SCRIPT_DIR/lib/local-deploy-lock.sh" \
    "$HOME/.local/share/code-agent-monitor/scripts/lib/local-deploy-lock.sh"
  do
    [ -n "$candidate" ] || continue
    [ -f "$candidate" ] || continue
    # shellcheck source=scripts/lib/local-deploy-lock.sh
    source "$candidate"
    return 0
  done

  printf '[cam-remote-install] error: local deploy lock library is missing; use the standalone release installer or run from a complete CAM checkout/package\n' >&2
  return 1
}

remote_install_on_exit() {
  local status="$?"
  trap - EXIT
  cam_local_deploy_lock_release
  if [ -n "$REMOTE_INSTALL_TMP" ] && [ "$KEEP_TMP" != "1" ]; then
    rm -rf "$REMOTE_INSTALL_TMP" 2>/dev/null || true
  fi
  exit "$status"
}

remote_install_on_int() {
  trap - INT
  exit 130
}

remote_install_on_term() {
  trap - TERM
  exit 143
}

log() {
  printf '[cam-remote-install] %s\n' "$*"
}

fail() {
  printf '[cam-remote-install] error: %s\n' "$*" >&2
  exit 1
}

need_cmd() {
  command -v "$1" >/dev/null 2>&1 || fail "$1 is required"
}

# curl "$@", plus the GITHUB_TOKEN bearer header when $1 is an api.github.com
# URL. The header goes through stdin (-H @-) so the token never shows up in ps
# or /proc/<pid>/cmdline, and curl (7.58+) drops Authorization when a redirect
# leaves the host, so the asset API's redirect to the storage CDN never
# carries it.
curl_github() {
  local url="$1" token=""
  shift
  case "$url" in
    https://api.github.com/*) token="${GITHUB_TOKEN:-${CAM_INSTALL_GITHUB_TOKEN:-}}" ;;
  esac
  if [ -z "$token" ]; then
    curl "$@"
  else
    printf 'Authorization: Bearer %s\n' "$token" | curl -H @- "$@"
  fi
}

curl_download_once() {
  local url="$1"
  local output="$2"
  shift 2

  curl_github "$url" -fL \
    "$CURL_HTTP_VERSION" \
    --connect-timeout "$CURL_CONNECT_TIMEOUT" \
    --max-time "$CURL_MAX_TIME" \
    --speed-time "$CURL_SPEED_TIME" \
    --speed-limit "$CURL_SPEED_LIMIT" \
    "$@" \
    "$url" \
    -o "$output"
}

curl_download() {
  local url="$1"
  local output="$2"
  shift 2

  curl -fL \
    "$CURL_HTTP_VERSION" \
    --connect-timeout "$CURL_CONNECT_TIMEOUT" \
    --max-time "$CURL_MAX_TIME" \
    --speed-time "$CURL_SPEED_TIME" \
    --speed-limit "$CURL_SPEED_LIMIT" \
    --retry "$CURL_RETRIES" \
    --retry-delay "$CURL_RETRY_DELAY" \
    --retry-all-errors \
    "$@" \
    "$url" \
    -o "$output"
}

# 小文件（release 元数据 / sha256 校验文件）使用小重试预算：大包共用的
# 50 次重试在代理对单个 URL 抽风时会让更新停滞近一小时，而这些请求
# 要么可以快速失败重选，要么本身就是 best-effort。代理环境失败后再用
# --noproxy '*' 直连兜底一次。
#
# api.github.com's unauthenticated rate limit is 60 requests/hour *per IP*,
# shared by everyone behind the same NAT/office network/proxy. When it's
# already exhausted, curl's `-f` turns the 403 into a bare exit 22 and the
# caller (release scanning) has no way to tell "rate limited" from "release
# genuinely doesn't exist" apart. Report the real HTTP status instead of
# letting that ambiguity surface as a misleading "no release found" error.
report_github_api_failure() {
  local url="$1"
  local http_code="$2"
  case "$url" in
    https://api.github.com/*) ;;
    *) return 0 ;;
  esac
  case "$http_code" in
    403 | 429)
      log "warning: GitHub API request failed (HTTP ${http_code}): ${url}"
      log "warning: this is almost always the unauthenticated rate limit (60 requests/hour per IP), not a missing release"
      log "warning: set GITHUB_TOKEN to raise the limit to 5000/hour (a fine-grained token with no extra permissions is enough), on the bash side of the pipe:"
      log "warning:   curl -fsSL https://github.com/${REPO}/releases/latest/download/install-remote.sh | GITHUB_TOKEN=<token> bash"
      log "warning: or retry after the hourly window resets"
      ;;
    "")
      log "warning: GitHub API request produced no response (network unreachable or timed out): ${url}"
      ;;
    *)
      log "warning: GitHub API request failed (HTTP ${http_code}): ${url}"
      ;;
  esac
}

curl_download_small() {
  local url="$1"
  local output="$2"
  shift 2

  local http_code rc=0
  http_code="$(curl_github "$url" -fL \
    "$CURL_HTTP_VERSION" \
    --connect-timeout "$CURL_CONNECT_TIMEOUT" \
    --max-time "$CURL_SMALL_MAX_TIME" \
    --retry "$CURL_SMALL_RETRIES" \
    --retry-delay "$CURL_RETRY_DELAY" \
    --retry-all-errors \
    -w '%{http_code}' \
    "$@" \
    "$url" \
    -o "$output")" || rc=$?
  if [ "$rc" -eq 0 ]; then
    return 0
  fi

  local proxy="${HTTPS_PROXY:-${https_proxy:-${HTTP_PROXY:-${http_proxy:-}}}}"
  if [ -n "$proxy" ]; then
    log "proxied download failed for $(basename "$output"); retrying once without proxy"
    rc=0
    http_code="$(curl_github "$url" -fL \
      "$CURL_HTTP_VERSION" \
      --noproxy '*' \
      --connect-timeout "$CURL_CONNECT_TIMEOUT" \
      --max-time "$CURL_SMALL_MAX_TIME" \
      --retry "$CURL_SMALL_RETRIES" \
      --retry-delay "$CURL_RETRY_DELAY" \
      --retry-all-errors \
      -w '%{http_code}' \
      "$@" \
      "$url" \
      -o "$output")" || rc=$?
    if [ "$rc" -eq 0 ]; then
      return 0
    fi
  fi

  report_github_api_failure "$url" "$http_code"
  return 1
}

downloaded_bytes() {
  if [ -f "$1" ]; then
    wc -c < "$1" | tr -d '[:space:]'
  else
    printf '0'
  fi
}

# Best-effort size of a public URL, for progress messages only. Requests that
# need extra curl arguments (API headers) are not probed.
remote_content_length() {
  [ "$#" -eq 1 ] || return 0
  # -I prints the headers of every hop, including error responses; only trust
  # Content-Length from a 2xx block.
  curl -fsSIL --max-time 15 "$1" 2>/dev/null \
    | awk '/^HTTP\// { size = 0; ok = ($2 ~ /^2/) } ok && tolower($1) == "content-length:" { size = $2 + 0 } END { if (size > 0) print size }' || true
}

format_download_progress() {
  local total="${2:-0}"
  [ "$total" != - ] || total=0
  awk -v done_bytes="$1" -v total="$total" 'BEGIN {
    if (total > 0) printf "%.1f of %.1f MB (%d%%)", done_bytes / 1048576, total / 1048576, done_bytes * 100 / total
    else printf "%.1f MB", done_bytes / 1048576
  }'
}

curl_download_resume_with_retries() {
  local retry_limit="$1"
  local url="$2"
  local output="$3"
  local attempt status before after total=""
  shift 3

  attempt=0
  while :; do
    before="$(downloaded_bytes "$output")"
    curl_download_once "$url" "$output" -C - "$@" && return 0
    status=$?
    # --max-time caps each attempt, so a slow but working link needs several
    # resumes for a large package. Attempts that add at least 256 KiB do not
    # use up the retry budget (which also bounds them by the package size); a
    # stalled or crawling link still fails after retry_limit attempts.
    after="$(downloaded_bytes "$output")"
    if [ "$after" -ge $((before + 262144)) ]; then
      # curl's meter restarts at 0% on every resume, so report overall progress.
      # Probe once; "-" remembers an unknown size so slow links are not re-probed.
      if [ -z "$total" ]; then
        total="$(remote_content_length "$url" "$@")"
        [ -n "$total" ] || total=-
      fi
      log "slow connection: $(format_download_progress "$after" "$total") downloaded; resuming automatically after ${CURL_RETRY_DELAY}s"
      sleep "$CURL_RETRY_DELAY"
      continue
    fi
    attempt=$((attempt + 1))
    if [ "$attempt" -gt "$retry_limit" ]; then
      return "$status"
    fi
    log "download interrupted; retrying with resume (${attempt}/${retry_limit}) after ${CURL_RETRY_DELAY}s"
    sleep "$CURL_RETRY_DELAY"
  done
}

curl_download_resume() {
  curl_download_resume_with_retries "$CURL_RETRIES" "$@"
}

log_proxy_hint() {
  local proxy="${HTTPS_PROXY:-${https_proxy:-${HTTP_PROXY:-${http_proxy:-}}}}"
  if [ -n "$proxy" ]; then
    log "using proxy from environment: $(printf '%s' "$proxy" | sed -E 's#(https?://)[^/@]+@#\1<auth>@#')"
  else
    log "no HTTP(S) proxy detected; set HTTPS_PROXY/HTTP_PROXY if downloads are slow"
  fi
}

install_downloaded_package() {
  local package_dir="$1"
  cam_first_run_prepare_access || return 1
  log "running package installer"
  export PATH="$HOME/.local/bin:$PATH"
  CAM_INSTALL_SERVICES="$INSTALL_SERVICES" CAM_INSTALL_BRIDGE_DEPS="$INSTALL_BRIDGE_DEPS" \
    LANG="$CAM_INSTALL_LOCALE" LC_ALL="$CAM_INSTALL_LOCALE" bash "$package_dir/install.sh"
  # Pinned legacy packages own neither service setup nor the dashboard command.
  # The downloader verifies their HTTP endpoints without invoking newer CLI APIs.
  if [ ! -f "$package_dir/scripts/lib/first-run.sh" ]; then
    if [ "$INSTALL_SERVICES" = 1 ]; then
      log "installing CAM launchd services (legacy package)"
      if ! LANG="$CAM_INSTALL_LOCALE" LC_ALL="$CAM_INSTALL_LOCALE" LOCAL_DASHBOARD_PORT=3456 "$HOME/.local/bin/cam" install; then
        fail "service startup failed; inspect the local service logs, resolve the problem and rerun this installer"
      fi
    fi
    LOCAL_DASHBOARD_PORT=3456 cam_first_run_finish "$HOME/.local/bin/cam" legacy
  fi
}

platform_slug() {
  local os arch slug supported_platforms="darwin-arm64 linux-x86_64"
  case "$(uname -s)" in
    Darwin) os="darwin" ;;
    Linux) os="linux" ;;
    MINGW*|MSYS*|CYGWIN*)
      fail "Windows Git Bash is not a supported CAM runtime; use install-windows.ps1 in Windows PowerShell to install the Linux package inside WSL2 (Ubuntu 22.04+, x86_64)"
      ;;
    *) fail "unsupported OS: $(uname -s)" ;;
  esac

  case "$(uname -m)" in
    arm64|aarch64) arch="arm64" ;;
    x86_64|amd64) arch="x86_64" ;;
    *) fail "unsupported architecture: $(uname -m)" ;;
  esac

  slug="${os}-${arch}"
  case " $supported_platforms " in
    *" $slug "*) printf '%s' "$slug" ;;
    *) fail "unsupported platform ${slug}; CAM currently publishes only: ${supported_platforms// /, }" ;;
  esac
}

linux_glibc_version() {
  local version=""
  if command -v getconf >/dev/null 2>&1; then
    version="$(getconf GNU_LIBC_VERSION 2>/dev/null | awk '{print $2}' || true)"
  fi
  if [ -z "$version" ] && command -v ldd >/dev/null 2>&1; then
    version="$(ldd --version 2>&1 | head -1 | grep -oE '[0-9]+\.[0-9]+$' || true)"
  fi
  printf '%s' "$version"
}

# Refuse before a ~40 MB download what install.sh would otherwise reject after
# it: the Linux binary links against glibc and cannot load on older hosts.
ensure_linux_glibc() {
  local version need_major="${LINUX_MIN_GLIBC%%.*}" need_minor="${LINUX_MIN_GLIBC#*.}"
  version="$(linux_glibc_version)"
  if ! [[ "$version" =~ ^([0-9]+)\.([0-9]+) ]]; then
    log "warning: could not detect the glibc version; the linux-x86_64 package needs glibc ${LINUX_MIN_GLIBC}+ and does not run on musl-based systems such as Alpine"
    return 0
  fi
  if [ $((10#${BASH_REMATCH[1]} * 1000 + 10#${BASH_REMATCH[2]})) -lt $((need_major * 1000 + need_minor)) ]; then
    fail "glibc ${version} is too old: the linux-x86_64 package needs glibc ${LINUX_MIN_GLIBC}+ (Ubuntu 22.04+, Debian 12+, RHEL/Rocky 9+)"
  fi
}

release_api_url() {
  if [ -n "$RELEASE_BASE_URL" ]; then
    printf '%s/%s/release.json' "$RELEASE_BASE_URL" "$1"
  else
    printf 'https://api.github.com/repos/%s/releases/tags/%s' "$REPO" "$1"
  fi
}

release_list_api_url() {
  if [ -n "$RELEASE_BASE_URL" ]; then
    printf '%s/index.json' "$RELEASE_BASE_URL"
  else
    printf 'https://api.github.com/repos/%s/releases?per_page=%s' "$REPO" "$RELEASE_SCAN_LIMIT"
  fi
}

json_string_value() {
  local key="$1"
  sed -nE "s/^[[:space:]]*\"${key}\":[[:space:]]*\"([^\"]+)\".*/\\1/p" | head -1
}

find_asset_url() {
  local json="$1"
  local slug="$2"
  grep -oE '"browser_download_url"[[:space:]]*:[[:space:]]*"[^"]+"' "$json" 2>/dev/null \
    | sed -nE 's/.*"browser_download_url"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/p' \
    | grep -E "cam-local-.*-${slug}\\.tar\\.gz$" \
    | head -1 || true
}

find_asset_api_url_by_name() {
  local json="$1"
  local name="$2"
  awk -v target="$name" '
    /"url"[[:space:]]*:[[:space:]]*"https:\/\/api\.github\.com\/repos\/.*\/releases\/assets\// {
      api_url = $0
      sub(/^[^"]*"url"[[:space:]]*:[[:space:]]*"/, "", api_url)
      sub(/".*$/, "", api_url)
    }
    /"name"[[:space:]]*:/ {
      asset_name = $0
      sub(/^[^"]*"name"[[:space:]]*:[[:space:]]*"/, "", asset_name)
      sub(/".*$/, "", asset_name)
      if (asset_name == target && api_url != "") {
        print api_url
        exit
      }
    }
    /^[[:space:]]*}[,]?[[:space:]]*$/ {
      api_url = ""
    }
  ' "$json" 2>/dev/null || true
}

release_tags_from_json() {
  local json="$1"
  grep -oE '"tag_name"[[:space:]]*:[[:space:]]*"[^"]+"' "$json" 2>/dev/null \
    | sed -nE 's/.*"tag_name"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/p' || true
}

asset_names_from_json() {
  local json="$1"
  grep -oE '"name"[[:space:]]*:[[:space:]]*"[^"]+"' "$json" 2>/dev/null \
    | sed -nE 's/.*"name"[[:space:]]*:[[:space:]]*"([^"]+)".*/\1/p' || true
}

release_has_asset_name() {
  local json="$1"
  local name="$2"
  asset_names_from_json "$json" | grep -Fxq "$name"
}

is_public_patch_zero_tag() {
  local tag="$1"
  [[ "$tag" =~ ^v[0-9]+\.[0-9]+\.0$ ]]
}

release_has_complete_public_assets() {
  local json="$1"
  local tag="$2"
  local version expected

  is_public_patch_zero_tag "$tag" || return 1
  if grep -Eq '"(draft|prerelease)"[[:space:]]*:[[:space:]]*true' "$json"; then
    return 1
  fi
  version="${tag#v}"
  for expected in \
    "cam-dashboard-${version}.apk" \
    "cam-dashboard-${version}.dmg" \
    "cam-local-${version}-darwin-arm64.tar.gz" \
    "cam-local-${version}-darwin-arm64.tar.gz.sha256" \
    "cam-local-${version}-linux-x86_64.tar.gz" \
    "cam-local-${version}-linux-x86_64.tar.gz.sha256" \
    "install-remote.sh"
  do
    release_has_asset_name "$json" "$expected" || return 1
  done
}

SELECTED_RELEASE_JSON=""

select_latest_release_json() {
  local slug="$1"
  local tmp="$2"
  local list_json tag safe_tag tag_json asset_url asset_name api

  list_json="$tmp/releases.json"
  api="$(release_list_api_url)"
  log "querying release list: $api"
  curl_download_small "$api" "$list_json" -sS

  for tag in $(release_tags_from_json "$list_json"); do
    if ! is_public_patch_zero_tag "$tag"; then
      log "skipping ${tag}: public release tags must end in .0"
      continue
    fi

    safe_tag="$(printf '%s' "$tag" | tr -c 'A-Za-z0-9._-' '_')"
    tag_json="$tmp/release-${safe_tag}.json"
    api="$(release_api_url "$tag")"
    log "checking release metadata: $api"
    curl_download_small "$api" "$tag_json" -sS

    if ! release_has_complete_public_assets "$tag_json" "$tag"; then
      log "skipping ${tag}: release is missing one or more combined public assets"
      continue
    fi

    asset_url="$(find_asset_url "$tag_json" "$slug")"
    if [ -z "$asset_url" ]; then
      log "skipping ${tag}: no local package asset for ${slug}"
      continue
    fi

    asset_name="$(basename "$asset_url")"
    if ! release_has_asset_name "$tag_json" "${asset_name}.sha256"; then
      log "skipping ${tag}: missing checksum for ${asset_name}"
      continue
    fi

    SELECTED_RELEASE_JSON="$tag_json"
    log "selected release ${tag} for ${slug}"
    return 0
  done

  return 1
}

main() {
  # Refuse unsupported hosts before the POSIX process checks in the deploy lock.
  local slug api tmp json asset_url asset_name asset_api_url archive package_dir release_tag
  slug="$(platform_slug)"
  case "$slug" in
    linux-*) ensure_linux_glibc ;;
  esac

  load_aperio_alias_library
  load_local_deploy_lock_library
  trap 'remote_install_on_exit' EXIT
  trap 'remote_install_on_int' INT
  trap 'remote_install_on_term' TERM
  cam_local_deploy_lock_acquire "$SCRIPT_SOURCE"

  load_first_run_library
  cam_first_run_mode
  cam_first_run_preflight
  # CLI-only downloads also prepare the dependency for historical packages.
  if [ "$INSTALL_SERVICES" != 1 ]; then
    case "${CAM_INSTALL_RUNTIME_DEPS:-1}" in
      1) ensure_tmux_runtime ;;
      0) ;;
      *) cam_first_run_block "CAM_INSTALL_RUNTIME_DEPS must be 0 or 1"; return 1 ;;
    esac
  fi

  need_cmd curl
  need_cmd tar
  need_cmd mktemp

  tmp="$(mktemp -d)"
  REMOTE_INSTALL_TMP="$tmp"

  if [ "$KEEP_TMP" = "1" ]; then
    log "keeping temp directory: $tmp"
  fi

  json="$tmp/release.json"
  log_proxy_hint
  if [ "$RELEASE" = "latest" ]; then
    if ! select_latest_release_json "$slug" "$tmp"; then
      fail "no complete public release found for ${slug}; expected a vX.Y.0 release with all combined assets"
    fi
    cp "$SELECTED_RELEASE_JSON" "$json"
  else
    [[ "$RELEASE" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || fail "release must be latest or vX.Y.Z"
    api="$(release_api_url "$RELEASE")"
    log "querying release metadata: $api"
    curl_download_small "$api" "$json" -sS
  fi

  release_tag="$(json_string_value tag_name < "$json" || true)"
  [ -z "$release_tag" ] || log "using release ${release_tag}"

  asset_url="$(find_asset_url "$json" "$slug")"
  if [ -z "$asset_url" ]; then
    fail "no release asset found for ${slug}; expected cam-local-.*-${slug}.tar.gz"
  fi

  asset_name="$(basename "$asset_url")"
  archive="$tmp/$asset_name"
  log "downloading $asset_name"
  if ! curl_download_resume_with_retries "$CURL_BROWSER_RETRIES" "$asset_url" "$archive"; then
    asset_api_url="$(find_asset_api_url_by_name "$json" "$asset_name")"
    if [ -z "$asset_api_url" ]; then
      fail "could not download ${asset_name} from ${asset_url%/*} (see the curl error above). Check the network connection (set HTTPS_PROXY if you use a proxy), then run the same install command again"
    fi
    log "browser download failed; retrying ${asset_name} through GitHub assets API"
    curl_download_resume "$asset_api_url" "$archive" -H "Accept: application/octet-stream" \
      || fail "download failed for ${asset_name} from both github.com and the GitHub assets API; set HTTPS_PROXY if github.com is unreachable, or GITHUB_TOKEN if api.github.com answered 403"
  fi

  # Verify sha256 checksum (best-effort: 缺失时跳过校验并告警)
  sha256_url="${asset_url}.sha256"
  sha256_file="$tmp/${asset_name}.sha256"
  log "downloading checksum"
  if ! curl_download_small "$sha256_url" "$sha256_file" -sS 2>/dev/null; then
    sha256_api_url="$(find_asset_api_url_by_name "$json" "${asset_name}.sha256")"
    if [ -n "$sha256_api_url" ]; then
      log "checksum download failed; retrying through GitHub assets API"
      curl_download_small "$sha256_api_url" "$sha256_file" -sS -H "Accept: application/octet-stream" 2>/dev/null || true
    fi
  fi

  if [ -f "$sha256_file" ] && [ -s "$sha256_file" ]; then
    expected_hash="$(awk '{print $1}' "$sha256_file")"
    if command -v shasum >/dev/null 2>&1; then
      actual_hash="$(shasum -a 256 "$archive" | awk '{print $1}')"
    elif command -v sha256sum >/dev/null 2>&1; then
      actual_hash="$(sha256sum "$archive" | awk '{print $1}')"
    else
      log "warning: no sha256 tool available, skipping verification"
      actual_hash=""
    fi
    if [ -n "$actual_hash" ]; then
      if [ "$expected_hash" != "$actual_hash" ]; then
        fail "sha256 checksum mismatch: expected $expected_hash, got $actual_hash"
      fi
      log "sha256 checksum verified"
    fi
  else
    log "warning: no checksum file found, skipping verification"
  fi

  log "extracting package"
  tar -xzf "$archive" -C "$tmp"
  package_dir="$(find "$tmp" -maxdepth 1 -type d -name 'cam-local-*' | head -1)"
  [ -n "$package_dir" ] || fail "archive did not contain cam-local-* directory"

  install_downloaded_package "$package_dir"
  if [ -f "$HOME/.local/bin/cam" ]; then
    cam_ensure_aperio_alias "$HOME/.local/bin"
  fi
  cam_configure_command_path "[cam-remote-install]" "$HOME/.local/bin" "$USER_PATH"

  log "installed cam: $(command -v cam || printf '%s/.local/bin/cam' "$HOME")"
  if cam_aperio_alias_is_owned "$HOME/.local/bin"; then
    log "aperio is available as an equivalent alias for cam"
  fi
  if [ -f "$package_dir/scripts/lib/first-run.sh" ]; then
    cam_first_run_access_hint
  else
    cam_first_run_access_hint legacy
  fi
}

# The official one-liner pipes this file into bash, so a truncated download must
# be inert: keep top-level code to definitions and run nothing before this line.
main "$@"
