#!/bin/sh
# Semanta CLI installer. Usage:  curl -fsSL https://get.semanta.dev | sh
#
# Downloads the latest `semanta` CLI for this OS/arch, verifies its SHA256 (the checksum
# and manifest are served over Cloudflare TLS; the binary itself does full minisign
# signature verification on every subsequent `semanta upgrade`), and installs it to
# ~/.local/bin (override with SEMANTA_INSTALL_DIR). Set SEMANTA_INSTALL_BASE to point at a
# different host. This script is POSIX sh; the Windows equivalent is install.ps1.
set -eu

BASE="${SEMANTA_INSTALL_BASE:-https://get.semanta.dev}"
DEST="${SEMANTA_INSTALL_DIR:-$HOME/.local/bin}"

say() { printf 'semanta: %s\n' "$1" >&2; }
die() { printf 'semanta: error: %s\n' "$1" >&2; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || die "required command '$1' not found"; }

need uname
need tar
if command -v curl >/dev/null 2>&1; then DL="curl -fsSL -o"; elif command -v wget >/dev/null 2>&1; then DL="wget -qO"; else die "need curl or wget"; fi

os=$(uname -s | tr '[:upper:]' '[:lower:]')
arch=$(uname -m)
case "$arch" in
  x86_64|amd64) arch=amd64 ;;
  aarch64|arm64) arch=arm64 ;;
  *) die "unsupported architecture: $arch" ;;
esac
case "$os" in
  linux|darwin) ;;
  *) die "unsupported OS: $os (on Windows run: irm https://get.semanta.dev/install.ps1 | iex)" ;;
esac
plat="${os}-${arch}"

tmp=$(mktemp -d 2>/dev/null || mktemp -d -t semanta)
trap 'rm -rf "$tmp"' EXIT INT TERM

# Resolve the current version from the signed manifest, then download the VERSIONED
# artifact. Versioned URLs are cached as immutable, so they should never skew — but if a
# release is ever re-cut under the same version, a CDN edge can end up holding an old
# tarball against a fresh checksum. verify_sha + the retry below self-heal that case by
# forcing a revalidation from origin (the manifest itself is served uncached).
$DL "$tmp/manifest.json" "${BASE}/manifest.json" || die "cannot reach ${BASE}/manifest.json"
ver=$(grep -o '"version"[[:space:]]*:[[:space:]]*"[^"]*"' "$tmp/manifest.json" | head -1 | sed 's/.*"\([^"]*\)"$/\1/')
[ -n "$ver" ] || die "could not read the latest version from the manifest"
tgz="semanta-${ver}-${plat}.tar.gz"
url="${BASE}/bin/${tgz}"

# verify_sha: check the downloaded tarball against its .sha256 sidecar. Returns non-zero
# on mismatch (does NOT exit) so the caller can retry.
verify_sha() (
  cd "$tmp"
  if command -v sha256sum >/dev/null 2>&1; then sha256sum -c "$tgz.sha256" >/dev/null 2>&1
  elif command -v shasum >/dev/null 2>&1; then shasum -a 256 -c "$tgz.sha256" >/dev/null 2>&1
  else die "no sha256 tool (sha256sum/shasum) available"; fi
)

# fetch <query>: download the tarball + its checksum sidecar. A non-empty query string
# gives the CDN a fresh cache key, forcing an origin revalidation on the retry.
fetch() {
  $DL "$tmp/$tgz" "$url$1" || die "no build for $plat in this release ($url)"
  $DL "$tmp/$tgz.sha256" "$url.sha256$1" || die "checksum download failed"
}

say "downloading semanta ${ver} ($plat)..."
fetch ""

say "verifying checksum..."
if ! verify_sha; then
  say "checksum mismatch — refetching from origin (bypassing a stale CDN cache)..."
  fetch "?nocache=$(date +%s 2>/dev/null || echo 0)-$$"
  verify_sha || die "SHA256 verification FAILED"
fi

tar -xzf "$tmp/$tgz" -C "$tmp" || die "extract failed"
[ -f "$tmp/semanta" ] || die "archive did not contain the semanta binary"

mkdir -p "$DEST" || die "cannot create $DEST"
install -m 0755 "$tmp/semanta" "$DEST/semanta" 2>/dev/null || { cp "$tmp/semanta" "$DEST/semanta" && chmod 0755 "$DEST/semanta"; } || die "install to $DEST failed"

ver=$("$DEST/semanta" version 2>/dev/null || echo "installed")
say "installed: $ver → $DEST/semanta"

case ":$PATH:" in
  *":$DEST:"*) ;;
  *) say "note: $DEST is not on your PATH. Add:  export PATH=\"$DEST:\$PATH\"" ;;
esac

cat >&2 <<EOF

Next steps:
  semanta login          # authenticate to your org
  semanta rollout        # register the bridge into your coding agents
  semanta upgrade        # self-update later (signature-verified)
EOF
