#!/bin/sh
# Installer for the `cs` code-search CLI.
#
#   curl -fsSL https://files.k6n.net/downloads/cs/install.sh | sh
#   curl -fsSL <base>/install.sh | sh -s -- --version 0.3.0 --dir /usr/local/bin
#   sh install-cs.sh --check        # installed vs latest
#   sh install-cs.sh --uninstall
#
# POSIX sh only (runs under dash, so it works with `curl | sh`).
#
# Platform detection: linux|darwin x amd64|arm64 (Rosetta-aware on macOS).
# Override with CS_PLATFORM=darwin-arm64.
#
# Layout at $CS_BASE (default below):
#   $CS_BASE/latest                          version string, e.g. "0.3.0"
#   $CS_BASE/<version>/cs-<os>-<arch>        the binary
#   $CS_BASE/<version>/cs-<os>-<arch>.sha256 "<sha256>  cs-<os>-<arch>" sidecar
# Each platform is published on its own, so no shared checksum file to race on.
set -eu

CS_BASE="${CS_BASE:-https://files.k6n.net/downloads/cs}"
CS_VERSION="${CS_VERSION:-}"
CS_DIR="${CS_DIR:-}"
CS_PLATFORM="${CS_PLATFORM:-}"
MODE=install

usage() {
  cat <<'EOF'
install-cs.sh: install the cs code-search CLI

usage: install-cs.sh [--version X.Y.Z] [--dir DIR] [--check] [--uninstall]

env: CS_VERSION, CS_DIR (default ~/.local/bin, or /usr/local/bin as root),
     CS_PLATFORM (e.g. darwin-arm64), CS_BASE (release base URL)
EOF
}

while [ $# -gt 0 ]; do
  case "$1" in
    --version) CS_VERSION="${2:-}"; shift 2 ;;
    --version=*) CS_VERSION="${1#--version=}"; shift ;;
    --dir) CS_DIR="${2:-}"; shift 2 ;;
    --dir=*) CS_DIR="${1#--dir=}"; shift ;;
    --check) MODE=check; shift ;;
    --uninstall) MODE=uninstall; shift ;;
    -h|--help) usage; exit 0 ;;
    *) echo "install-cs: unknown option $1" >&2; usage >&2; exit 1 ;;
  esac
done

die() { echo "install-cs: $*" >&2; exit 1; }

need() { command -v "$1" >/dev/null 2>&1 || die "missing required command: $1"; }
need curl
need uname
need mktemp

if [ -z "$CS_DIR" ]; then
  if [ "$(id -u)" = "0" ]; then CS_DIR=/usr/local/bin; else CS_DIR="$HOME/.local/bin"; fi
fi
TARGET="$CS_DIR/cs"

detect_platform() {
  os="$(uname -s | tr '[:upper:]' '[:lower:]')"
  case "$os" in
    linux|darwin) ;;
    *) die "unsupported OS: $os (linux and darwin only)" ;;
  esac

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

  # Apple Silicon running this script under Rosetta reports x86_64.
  if [ "$os" = darwin ] && [ "$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)" = 1 ]; then
    arch=arm64
  fi

  printf '%s-%s' "$os" "$arch"
}

if [ -n "$CS_PLATFORM" ]; then PLATFORM="$CS_PLATFORM"; else PLATFORM="$(detect_platform)"; fi

if command -v sha256sum >/dev/null 2>&1; then
  SHA="sha256sum"
elif command -v shasum >/dev/null 2>&1; then
  SHA="shasum -a 256"
else
  die "missing sha256sum or shasum"
fi

installed_version() {
  if [ -x "$TARGET" ]; then
    "$TARGET" version 2>/dev/null | awk 'NR==1{print $2}' | tr -d 'v' || true
  fi
}

latest_version() {
  if [ -n "$CS_VERSION" ]; then printf '%s' "$CS_VERSION"; return; fi
  curl -fsSL --retry 3 "$CS_BASE/latest" 2>/dev/null | tr -d ' \r\nv' || true
}

if [ "$MODE" = "uninstall" ]; then
  rm -f "$TARGET"
  echo "install-cs: removed $TARGET"
  exit 0
fi

WANT="$(latest_version)"
[ -n "$WANT" ] || die "cannot resolve latest version (set CS_VERSION=X.Y.Z)"

if [ "$MODE" = "check" ]; then
  IV="$(installed_version)"
  if [ -z "$IV" ]; then echo "cs: not installed (latest $WANT, $PLATFORM)"
  elif [ "$IV" = "$WANT" ]; then echo "cs: $IV up to date ($PLATFORM)"
  else echo "cs: $IV installed, $WANT available -> re-run the installer"; fi
  exit 0
fi

ASSET="cs-$PLATFORM"
URL="$CS_BASE/$WANT/$ASSET"
SUM_URL="$URL.sha256"

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT INT TERM

echo "install-cs: cs $WANT for $PLATFORM"
curl -fsSL --retry 3 "$URL" -o "$TMP/$ASSET" \
  || die "no build of cs $WANT for $PLATFORM at $URL (not published yet?)"

# No checksum, no install: refuse rather than run an unverified binary.
curl -fsSL --retry 3 "$SUM_URL" -o "$TMP/$ASSET.sha256" \
  || die "missing checksum at $SUM_URL; refusing to install unverified binary"
EXPECTED="$(awk '{print $1; exit}' "$TMP/$ASSET.sha256")"
ACTUAL="$(cd "$TMP" && $SHA "$ASSET" | awk '{print $1}')"
[ -n "$EXPECTED" ] && [ "$EXPECTED" = "$ACTUAL" ] \
  || die "checksum mismatch for $ASSET (expected ${EXPECTED:-none}, got $ACTUAL)"
echo "install-cs: checksum ok"

mkdir -p "$CS_DIR"
chmod 0755 "$TMP/$ASSET"
mv "$TMP/$ASSET" "$TARGET"
echo "install-cs: installed $TARGET"
"$TARGET" version || true

case ":$PATH:" in
  *":$CS_DIR:"*) ;;
  *) echo "hint: add $CS_DIR to PATH: export PATH=\"$CS_DIR:\$PATH\"" ;;
esac
