#!/bin/sh
# Loctree CLI installer (stable registry lane)
#
# Usage:
#   curl -fsSL https://loct.io/install.sh | sh
#
# Env overrides:
#   LOCTREE_VERSION   exact release version (default: live registry current)
#   INSTALL_DIR       where binaries/wrappers are placed (default: ~/.local/bin)
#   CARGO_HOME        cargo home for the EXPLICIT source fallback (default: ~/.cargo)
#   LOCTREE_BASE_URL  release base URL (default: https://loctree.com/releases)
#   LOCTREE_GPG_KEY_URL  release signing public key URL (default: https://loctree.com/loctree-signing.asc)
#   LOCTREE_GPG_FINGERPRINT  expected release key fingerprint
#   LOCTREE_REQUIRE_GPG=1  fail if the GPG key or .sig sidecar is unavailable (default: 1)
#   LOCTREE_ALLOW_CARGO_FALLBACK=1  EXPLICIT opt-in: fall back to `cargo install`
#                     when the prebuilt bundle cannot be installed. This is NOT
#                     a verified Loctree release install (no SHA256/GPG channel
#                     verification, possibly older version, no aicx binaries).
#                     Never enabled implicitly.
#   LOCTREE_MACOS_TEAM_ID  expected Apple TeamIdentifier (extra layer on macOS)
#   LOCTREE_NO_PROFILE_UPDATE=1  do not edit ~/.zshrc when PATH is missing
#
# Design notes (0.12.3 hardening, vs the 0.10.2 installer):
#   - NO silent cargo fallback: any download/verification failure fails loudly.
#     Cargo fallback exists ONLY behind LOCTREE_ALLOW_CARGO_FALLBACK=1 and is
#     clearly labelled as an unverified install.
#   - GPG is the trust root and is NOT substitutable: macOS codesign verify is
#     an ADDITIONAL layer on darwin, never a replacement for GPG.
#   - Artifact names are resolved from the release manifest.json (artifacts
#     carry the suite commit SHA in the file name, e.g.
#     loctree-0.12.3-g45cf015-<target>.tar.gz). Legacy name format is used only
#     when no manifest is available (older versions via LOCTREE_VERSION).
#   - Prints version + loctree-suite commit SHA and runs `loct --version` as a
#     post-install check (hard fail if the binary does not run).
#   - Whole script runs through main() invoked on the last line, so a
#     truncated `curl | sh` transfer executes nothing.

set -eu
umask 022

VERSION="${LOCTREE_VERSION:-}"
INSTALL_DIR="${INSTALL_DIR:-"$HOME/.local/bin"}"
CARGO_HOME="${CARGO_HOME:-"$HOME/.cargo"}"
CARGO_BIN="$CARGO_HOME/bin"
BASE_URL="${LOCTREE_BASE_URL:-https://loctree.com/releases}"
GPG_KEY_URL="${LOCTREE_GPG_KEY_URL:-${BASE_URL%/releases}/loctree-signing.asc}"
GPG_FINGERPRINT="${LOCTREE_GPG_FINGERPRINT:-8868139E8A9A2291D067135FB979B60C7079E4D4}"
REQUIRE_GPG="${LOCTREE_REQUIRE_GPG:-1}"
ALLOW_CARGO_FALLBACK="${LOCTREE_ALLOW_CARGO_FALLBACK:-0}"
MACOS_TEAM_ID="${LOCTREE_MACOS_TEAM_ID:-MW223P3NPX}"
RELEASE_BINARIES="loct loctree loctree-mcp loctree-lsp aicx aicx-mcp"

# Filled during install for the final summary.
LOCTREE_COMMIT=""
INSTALLED_VIA="prebuilt"

red() { printf '\033[0;31m%s\033[0m\n' "$*"; }
green() { printf '\033[0;32m%s\033[0m\n' "$*"; }
yellow() { printf '\033[0;33m%s\033[0m\n' "$*"; }
blue() { printf '\033[0;34m%s\033[0m\n' "$*"; }

need_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    red "missing required command: $1"
    exit 1
  fi
}

resolve_version() {
  if [ -z "$VERSION" ]; then
    need_cmd curl
    index_url="$BASE_URL/index.json"
    if ! index_json="$(curl -fsSL "$index_url" 2>/dev/null)"; then
      red "release index unavailable: $index_url"
      exit 1
    fi
    VERSION="$(printf '%s' "$index_json" \
      | tr '\n' ' ' \
      | sed -n 's/.*"current"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')"
    if [ -z "$VERSION" ]; then
      red "release index has no current version: $index_url"
      exit 1
    fi
    green "stable release (from index): $VERSION"
  fi
  if ! printf '%s\n' "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; then
    red "invalid Loctree release version: $VERSION"
    exit 1
  fi
}

sha256_file() {
  if command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$1" | awk '{print $1}'
  elif command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$1" | awk '{print $1}'
  else
    red "missing shasum or sha256sum for release verification"
    exit 1
  fi
}

skip_signature_verification() {
  reason="$1"
  if [ "$REQUIRE_GPG" = "1" ]; then
    red "strict mode (LOCTREE_REQUIRE_GPG=1) requires GPG verification: $reason"
    exit 1
  fi
  yellow "$reason; skipping signature verification (LOCTREE_REQUIRE_GPG=0)"
}

normalize_fingerprint() {
  printf '%s' "$1" | tr -d '[:space:]' | tr '[:lower:]' '[:upper:]'
}

target_triple() {
  os="$(uname -s | tr '[:upper:]' '[:lower:]')"
  arch="$(uname -m)"
  case "$os:$arch" in
    darwin:arm64|darwin:aarch64) printf 'aarch64-apple-darwin' ;;
    linux:x86_64|linux:amd64) printf 'x86_64-unknown-linux-gnu' ;;
    linux:aarch64|linux:arm64) printf 'aarch64-unknown-linux-gnu' ;;
    *) printf '' ;;
  esac
}

# Loud failure of the prebuilt path. Exits unless the operator explicitly
# opted into the unverified cargo fallback, in which case it returns 1 so the
# caller can run the fallback.
prebuilt_failure() {
  reason="$1"
  red "prebuilt release install failed: $reason"
  if [ "$ALLOW_CARGO_FALLBACK" = "1" ]; then
    yellow "LOCTREE_ALLOW_CARGO_FALLBACK=1 is set; continuing with the UNVERIFIED cargo fallback"
    return 1
  fi
  red "refusing to fall back to cargo silently."
  red "fix the download/verification problem, or re-run with"
  red "LOCTREE_ALLOW_CARGO_FALLBACK=1 to explicitly accept an UNVERIFIED cargo install."
  exit 1
}

# Extract the artifact file name for a target from a version manifest.json.
# POSIX sh, no jq: split JSON on commas/braces (URLs and file names contain
# neither), then pull the first quoted string that ends in "-<target>.tar.gz"
# and strip any URL path prefix. Works on pretty-printed and minified JSON,
# and on the live 0.10.2 manifest (its "url" fields match the same shape).
manifest_artifact_name() {
  manifest_file="$1"
  mf_target="$2"
  raw="$(tr ',{}' '\n\n\n' < "$manifest_file" \
    | sed -n 's/.*"\([^"]*-'"$mf_target"'\.tar\.gz\)".*/\1/p' \
    | head -n 1)"
  [ -n "$raw" ] || return 1
  printf '%s\n' "${raw##*/}"
}

# Extract a top-level commit value from JSON (components/loctree-suite.json
# uses "commit", the release manifest uses "loctree_suite_commit").
json_commit_value() {
  json_file="$1"
  json_key="$2"
  sed -n 's/.*"'"$json_key"'"[[:space:]]*:[[:space:]]*"\([0-9a-fA-F]\{7,40\}\)".*/\1/p' \
    "$json_file" | head -n 1
}

# GPG verification — the trust root. NOT substitutable by codesign.
verify_gpg_signature() {
  file="$1"
  base_url="$2"
  tmp="$3"
  sig_file="$file.sig"
  pub_file="$tmp/loctree-signing.asc"
  sums_file="$tmp/SHA256SUMS"
  gnupg_home="$tmp/gnupg"
  expected_fingerprint="$(normalize_fingerprint "$GPG_FINGERPRINT")"

  if ! command -v gpg >/dev/null 2>&1; then
    skip_signature_verification "gpg unavailable"
    return 0
  fi
  if ! curl -fsSL "$GPG_KEY_URL" -o "$pub_file" 2>/dev/null; then
    skip_signature_verification "GPG signing key unavailable ($GPG_KEY_URL)"
    return 0
  fi
  actual_fingerprint="$(gpg --batch --with-colons --import-options show-only --import "$pub_file" 2>/dev/null | awk -F: '$1 == "fpr" {print $10; exit}')"
  actual_fingerprint="$(normalize_fingerprint "$actual_fingerprint")"
  if [ -z "$actual_fingerprint" ]; then
    red "GPG signing key fingerprint could not be read"
    exit 1
  fi
  if [ "$actual_fingerprint" != "$expected_fingerprint" ]; then
    red "GPG signing key fingerprint mismatch"
    printf 'expected: %s\nactual:   %s\n' "$expected_fingerprint" "$actual_fingerprint"
    exit 1
  fi

  # Cross-check against the per-version SHA256SUMS. If the file exists but
  # has no entry for our artifact, that is an inconsistency — fail in strict
  # mode. If the file cannot be fetched at all (older releases like 0.9.4
  # never published one), warn and rely on the mandatory .sha256 sidecar +
  # GPG signature below.
  file_name="$(basename "$file")"
  if curl -fsSL "$base_url/SHA256SUMS" -o "$sums_file" 2>/dev/null; then
    expected="$(awk -v name="$file_name" '$2 == name {print $1}' "$sums_file")"
    if [ -n "$expected" ]; then
      actual="$(sha256_file "$file")"
      if [ "$actual" != "$expected" ]; then
        red "checksum mismatch for $file_name (SHA256SUMS)"
        printf 'expected: %s\nactual:   %s\n' "$expected" "$actual"
        exit 1
      fi
      green "SHA256SUMS ok: $actual"
    else
      if [ "$REQUIRE_GPG" = "1" ]; then
        red "SHA256SUMS exists but has no entry for $file_name (strict mode)"
        exit 1
      fi
      yellow "SHA256SUMS has no entry for $file_name"
    fi
  else
    yellow "per-version SHA256SUMS unavailable; relying on .sha256 sidecar + GPG signature"
  fi

  if ! curl -fsSL "$base_url/$(basename "$sig_file")" -o "$sig_file" 2>/dev/null; then
    skip_signature_verification "signature sidecar unavailable ($base_url/$(basename "$sig_file"))"
    return 0
  fi
  mkdir -p "$gnupg_home"
  chmod 700 "$gnupg_home"
  if GNUPGHOME="$gnupg_home" gpg --batch --quiet --import "$pub_file" >/dev/null 2>&1 \
    && GNUPGHOME="$gnupg_home" gpg --batch --quiet --verify "$sig_file" "$file" >/dev/null 2>&1; then
    green "GPG signature ok"
  else
    red "signature verification failed for $(basename "$file")"
    exit 1
  fi
}

# macOS codesign check — ADDITIONAL layer on darwin, on top of (never instead
# of) GPG. Returns 1 when the layer cannot run (no codesign, no payload);
# hard-fails when an actual signature/TeamIdentifier verification fails.
verify_macos_codesign_archive() {
  file="$1"
  cs_target="$2"
  tmp="$3"
  case "$cs_target" in
    *apple-darwin) ;;
    *) return 1 ;;
  esac
  if ! command -v codesign >/dev/null 2>&1; then
    return 1
  fi

  check_dir="$tmp/codesign-check"
  rm -rf "$check_dir"
  mkdir -p "$check_dir"
  tar -xzf "$file" -C "$check_dir"
  # The archive file may be SHA-renamed; the inner directory keeps the
  # pristine build name. Resolve it by glob instead of assuming.
  payload=""
  for d in "$check_dir"/loctree-*/; do
    if [ -d "${d}bin" ]; then
      payload="${d}bin"
      break
    fi
  done
  if [ -z "$payload" ]; then
    return 1
  fi

  verified=0
  for bin in $RELEASE_BINARIES; do
    bin_path="$payload/$bin"
    [ -f "$bin_path" ] || continue
    if ! codesign --verify --verbose=2 "$bin_path" >/dev/null 2>&1; then
      red "macOS code signature verification failed for $bin"
      exit 1
    fi
    actual_team="$(codesign -dv "$bin_path" 2>&1 | awk -F= '$1 == "TeamIdentifier" {print $2; exit}')"
    if [ "$actual_team" != "$MACOS_TEAM_ID" ]; then
      red "macOS code signature TeamIdentifier mismatch for $bin"
      printf 'expected: %s\nactual:   %s\n' "$MACOS_TEAM_ID" "${actual_team:-unknown}"
      exit 1
    fi
    verified=$((verified + 1))
  done

  if [ "$verified" -eq 0 ]; then
    return 1
  fi
  green "macOS code signatures ok: $verified binaries (TeamIdentifier $MACOS_TEAM_ID) [additional layer]"
  return 0
}

install_binary_from_payload() {
  bin="$1"
  src="$2"
  install -m 0755 "$src" "$INSTALL_DIR/$bin"
  printf '  %s -> %s\n' "$bin" "$INSTALL_DIR/$bin"
}

install_payload_binaries() {
  payload="$1"
  mkdir -p "$INSTALL_DIR"
  installed_names=""
  installed_count=0

  for bin in $RELEASE_BINARIES; do
    if [ -f "$payload/$bin" ]; then
      install_binary_from_payload "$bin" "$payload/$bin"
      installed_names="$installed_names $bin"
      installed_count=$((installed_count + 1))
    fi
  done

  for bin_path in "$payload"/*; do
    [ -e "$bin_path" ] || continue
    [ -f "$bin_path" ] && [ -x "$bin_path" ] || continue
    bin="${bin_path##*/}"
    case " $installed_names " in
      *" $bin "*) continue ;;
    esac
    install_binary_from_payload "$bin" "$bin_path"
    installed_names="$installed_names $bin"
    installed_count=$((installed_count + 1))
  done

  if [ "$installed_count" -eq 0 ]; then
    red "no installable binaries found in $payload"
    exit 1
  fi
}

install_prebuilt() {
  target="$1"
  artifact_base="$BASE_URL/$VERSION"
  tmp="$(mktemp -d)"
  trap 'rm -rf "$tmp"' EXIT

  blue "[1/5] resolving release artifact"
  need_cmd curl
  need_cmd tar

  # Resolve the artifact name from the version manifest. 0.12.3+ artifacts
  # embed the suite commit SHA in the name (loctree-0.12.3-g45cf015-<target>);
  # the manifest is the source of truth for the exact file name.
  archive=""
  manifest_file="$tmp/manifest.json"
  if curl -fsSL "$artifact_base/manifest.json" -o "$manifest_file" 2>/dev/null; then
    if archive="$(manifest_artifact_name "$manifest_file" "$target")"; then
      green "artifact (from manifest): $archive"
    else
      archive=""
      if grep -q '"artifacts"' "$manifest_file" 2>/dev/null; then
        # Manifest lists artifacts but none for this target: the release does
        # not ship this platform. Do not guess legacy URLs.
        prebuilt_failure "release $VERSION does not provide a bundle for $target (per manifest.json)" || return 1
      fi
      yellow "manifest.json has no artifact entries; using legacy artifact name"
    fi
  else
    yellow "manifest.json unavailable for $VERSION; using legacy artifact name"
  fi
  if [ -z "$archive" ]; then
    # Compatibility path for older versions (e.g. LOCTREE_VERSION=0.9.5).
    archive="loctree-$VERSION-$target.tar.gz"
  fi
  url="$artifact_base/$archive"
  sha_url="$url.sha256"

  blue "[2/5] downloading release bundle"
  if ! curl -fsSL "$url" -o "$tmp/$archive"; then
    prebuilt_failure "release bundle download failed: $url" || return 1
  fi
  if ! curl -fsSL "$sha_url" -o "$tmp/$archive.sha256"; then
    prebuilt_failure "checksum sidecar download failed: $sha_url" || return 1
  fi

  blue "[3/5] verifying SHA256 + signatures"
  expected="$(awk '{print $1}' "$tmp/$archive.sha256")"
  actual="$(sha256_file "$tmp/$archive")"
  if [ "$actual" != "$expected" ]; then
    red "checksum mismatch for $archive"
    printf 'expected: %s\nactual:   %s\n' "$expected" "$actual"
    exit 1
  fi
  green "checksum ok: $actual"

  # Trust root: GPG. Hard requirement under LOCTREE_REQUIRE_GPG=1.
  verify_gpg_signature "$tmp/$archive" "$artifact_base" "$tmp"

  # Additional platform layer on macOS (never a GPG substitute).
  case "$target" in
    *apple-darwin)
      if ! verify_macos_codesign_archive "$tmp/$archive" "$target" "$tmp"; then
        yellow "macOS codesign layer skipped (codesign or payload unavailable); GPG remains the trust root"
      fi
      ;;
  esac

  blue "[4/5] installing binaries"
  extract_dir="$tmp/extract"
  mkdir -p "$extract_dir"
  tar -xzf "$tmp/$archive" -C "$extract_dir"
  # Inner directory keeps the pristine build name (no commit SHA), so resolve
  # it by glob rather than deriving it from the archive file name.
  bundle_root=""
  for d in "$extract_dir"/loctree-*/; do
    if [ -d "${d}bin" ]; then
      bundle_root="${d%/}"
      break
    fi
  done
  if [ -z "$bundle_root" ]; then
    red "release bundle layout unexpected: no loctree-*/bin directory found"
    exit 1
  fi
  install_payload_binaries "$bundle_root/bin"

  # Record the loctree-suite commit for the final summary: prefer the bundle
  # metadata, fall back to the release manifest.
  if [ -f "$bundle_root/components/loctree-suite.json" ]; then
    LOCTREE_COMMIT="$(json_commit_value "$bundle_root/components/loctree-suite.json" "commit")"
  fi
  if [ -z "$LOCTREE_COMMIT" ] && [ -f "$manifest_file" ]; then
    LOCTREE_COMMIT="$(json_commit_value "$manifest_file" "loctree_suite_commit")"
  fi
  return 0
}

install_from_cargo() {
  INSTALLED_VIA="cargo"
  yellow "============================================================"
  yellow "WARNING: cargo fallback is NOT a verified Loctree install:"
  yellow "  - no release SHA256 / GPG channel verification"
  yellow "  - crates.io may serve an OLDER version than $VERSION"
  yellow "  - aicx / aicx-mcp / loctree-lsp are NOT installed this way"
  yellow "Prefer the prebuilt bundle from $BASE_URL."
  yellow "============================================================"
  need_cmd cargo
  mkdir -p "$CARGO_BIN"

  blue "installing from Cargo (explicit fallback)"
  cargo install loctree --force
  cargo install loctree-mcp --force || true

  mkdir -p "$INSTALL_DIR"
  for bin in loct loctree loctree-mcp; do
    if [ -x "$CARGO_BIN/$bin" ]; then
      ln -sf "$CARGO_BIN/$bin" "$INSTALL_DIR/$bin" 2>/dev/null || cp "$CARGO_BIN/$bin" "$INSTALL_DIR/$bin"
      printf '  %s -> %s\n' "$bin" "$INSTALL_DIR/$bin"
    fi
  done
}

ensure_path() {
  blue "[5/5] checking PATH"
  case ":$PATH:" in
    *":$INSTALL_DIR:"*) green "$INSTALL_DIR is already in PATH"; return ;;
  esac

  if [ "${LOCTREE_NO_PROFILE_UPDATE:-}" = "1" ]; then
    yellow "$INSTALL_DIR is not in PATH; profile update skipped"
    return
  fi

  profile="$HOME/.zshrc"
  if [ -w "$profile" ] && ! grep -q "loctree installer" "$profile" 2>/dev/null; then
    {
      printf '\n# loctree installer\n'
      printf 'export PATH="%s:$PATH"\n' "$INSTALL_DIR"
    } >>"$profile"
    yellow "added $INSTALL_DIR to $profile; reload your shell or run: source $profile"
  else
    yellow "$INSTALL_DIR is not in PATH"
  fi
}

post_install_check() {
  blue "post-install check"
  if [ ! -x "$INSTALL_DIR/loct" ]; then
    red "post-install check failed: $INSTALL_DIR/loct is missing or not executable"
    exit 1
  fi
  if ! version_output="$("$INSTALL_DIR/loct" --version 2>&1)"; then
    red "post-install check failed: $INSTALL_DIR/loct --version exited non-zero"
    printf '%s\n' "$version_output"
    exit 1
  fi
  green "loct --version: $version_output"
}

main() {
  printf '\n'
  blue "Loctree installer"
  resolve_version
  printf 'version: %s\ninstall: %s\nsource:  %s\n\n' "$VERSION" "$INSTALL_DIR" "$BASE_URL"

  target="$(target_triple)"
  if [ -z "$target" ]; then
    if ! prebuilt_failure "no prebuilt bundle for this platform: $(uname -s)/$(uname -m)"; then
      install_from_cargo
    fi
  else
    if ! install_prebuilt "$target"; then
      # Only reachable when LOCTREE_ALLOW_CARGO_FALLBACK=1 (prebuilt_failure
      # exits otherwise).
      install_from_cargo
    fi
  fi

  ensure_path
  post_install_check

  printf '\n'
  green "Installation complete"
  printf 'installed:        loctree %s (%s)\n' "$VERSION" "$INSTALLED_VIA"
  printf 'loctree commit:   %s\n' "${LOCTREE_COMMIT:-unknown}"
  printf 'try:\n'
  printf '  %s/loct --version\n' "$INSTALL_DIR"
  printf '  %s/loct scan\n' "$INSTALL_DIR"
  printf '  %s/loct --for-ai\n' "$INSTALL_DIR"
  printf '\n'
}

main "$@"
