#!/bin/sh
# Tempo CLI installer.  Usage:
#
#   curl -fsSL https://get.tempo.rb2.dev/install.sh | sh
#
# Downloads the latest `tempo` binary for this platform from the public R2 dist
# bucket and installs it. Because curl (unlike a browser) doesn't set the macOS
# `com.apple.quarantine` attribute, the binary runs without the Gatekeeper
# "damaged" prompt. Override the install dir with TEMPO_INSTALL_DIR.
#
# `https://get.tempo.rb2.dev` is substituted with the real r2.dev URL at publish time.
set -eu

BASE="https://get.tempo.rb2.dev"
INSTALL_DIR="${TEMPO_INSTALL_DIR:-$HOME/.local/bin}"

fail() {
  echo "tempo install: $1" >&2
  exit 1
}

command -v curl >/dev/null 2>&1 || fail "curl is required"

# Map uname to the published asset name (must match the release build targets).
os="$(uname -s)"
arch="$(uname -m)"
case "$os" in
  Darwin) os="darwin" ;;
  Linux) os="linux" ;;
  *) fail "unsupported OS '$os' — download a binary manually from $BASE" ;;
esac
case "$arch" in
  arm64 | aarch64) arch="arm64" ;;
  x86_64 | amd64) arch="x64" ;;
  *) fail "unsupported architecture '$arch'" ;;
esac
asset="tempo-${os}-${arch}"

# Resolve the latest version from the manifest (no jq dependency).
version="$(curl -fsSL "$BASE/cli/latest.json" | sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p')"
[ -n "$version" ] || fail "could not resolve the latest version from $BASE/cli/latest.json"

url="$BASE/cli/v${version}/${asset}"
echo "tempo install: v${version} ($asset) -> ${INSTALL_DIR}/tempo"

mkdir -p "$INSTALL_DIR"
tmp="$(mktemp "${TMPDIR:-/tmp}/tempo.XXXXXX")"
trap 'rm -f "$tmp"' EXIT
curl -fSL --progress-bar "$url" -o "$tmp" || fail "download failed: $url"
# Defensive: strip a quarantine flag if some wrapper set one (curl normally won't).
command -v xattr >/dev/null 2>&1 && xattr -d com.apple.quarantine "$tmp" 2>/dev/null || true
chmod +x "$tmp"
mv "$tmp" "${INSTALL_DIR}/tempo"
trap - EXIT

echo "tempo install: done — $("${INSTALL_DIR}/tempo" version) at ${INSTALL_DIR}/tempo"
case ":$PATH:" in
  *":$INSTALL_DIR:"*) ;;
  *) echo "tempo install: add ${INSTALL_DIR} to your PATH to run 'tempo' directly" >&2 ;;
esac
