#!/bin/sh
# mcppipe CLI installer — served at https://mcppipe.sh
#
#   curl -fsSL https://mcppipe.sh | sh
#
# Downloads the latest mcppipe binary from the PUBLIC release repo
# (github.com/mcppipe/dist — binaries only, no source) and installs it.
# The mcppipe source lives in a private repo; only built artifacts are public.
set -eu

REPO="mcppipe/dist"
BASE="https://github.com/${REPO}/releases/latest/download"
BIN="mcppipe"

say() { printf '  %s\n' "$*"; }
err() { printf 'error: %s\n' "$*" >&2; exit 1; }

# --- detect platform → cargo-dist target triple ---------------------------
os="$(uname -s)"
arch="$(uname -m)"
case "$os" in
  Linux)  plat="unknown-linux-gnu" ;;
  Darwin) plat="apple-darwin" ;;
  *) err "unsupported OS '$os' — on Windows run:  irm https://mcppipe.sh/install.ps1 | iex" ;;
esac
case "$arch" in
  x86_64|amd64)  cpu="x86_64" ;;
  arm64|aarch64) cpu="aarch64" ;;
  *) err "unsupported architecture '$arch'" ;;
esac
target="${cpu}-${plat}"
archive="${BIN}-${target}.tar.xz"   # cargo-dist archive name
url="${BASE}/${archive}"

# --- download + install ---------------------------------------------------
install_dir="${MCPPIPE_INSTALL_DIR:-$HOME/.local/bin}"
mkdir -p "$install_dir"

tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT

say "downloading ${archive} …"
if command -v curl >/dev/null 2>&1; then
  curl -fsSL "$url" -o "$tmp/$archive" || err "download failed: $url"
elif command -v wget >/dev/null 2>&1; then
  wget -qO "$tmp/$archive" "$url" || err "download failed: $url"
else
  err "need curl or wget on PATH"
fi

say "extracting …"
tar -xJf "$tmp/$archive" -C "$tmp" 2>/dev/null || err "extract failed (need tar with xz support)"
binpath="$(find "$tmp" -type f -name "$BIN" 2>/dev/null | head -n1)"
[ -n "$binpath" ] || err "binary '$BIN' not found inside $archive"
install -m 0755 "$binpath" "$install_dir/$BIN"

say "installed $BIN → $install_dir/$BIN"
case ":$PATH:" in
  *":$install_dir:"*) ;;
  *) say "add it to your PATH:  export PATH=\"$install_dir:\$PATH\"" ;;
esac
"$install_dir/$BIN" --version 2>/dev/null || true
