#!/bin/sh
# Klovius agent installer.  Usage:  curl -fsSL https://get.klovius.sh | sh
# Env overrides: KLOVIUS_VERSION=<x.y.z>  KLOVIUS_DL_BASE=<url>  KLOVIUS_DRY_RUN=1
set -eu

DL_BASE="${KLOVIUS_DL_BASE:-https://dl.klovius.sh}"
BIN="klovius"

err() { echo "klovius-install: $*" >&2; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || err "required tool not found: $1"; }

need uname
need tar

# Detect OS + arch -> Rust target triple.
os="$(uname -s)"
arch="$(uname -m)"
case "$os" in
  Darwin) case "$arch" in
            arm64|aarch64) target="aarch64-apple-darwin" ;;
            x86_64)        target="x86_64-apple-darwin" ;;
            *) err "unsupported macOS arch: $arch" ;;
          esac ;;
  Linux)  case "$arch" in
            aarch64|arm64) target="aarch64-unknown-linux-musl" ;;
            x86_64)        target="x86_64-unknown-linux-musl" ;;
            *) err "unsupported Linux arch: $arch" ;;
          esac ;;
  *) err "unsupported OS: $os (Windows: see https://klovius.sh/docs)" ;;
esac

# A sha256 tool (name differs by platform).
if command -v sha256sum >/dev/null 2>&1; then
  sha_check() { sha256sum -c "$1" >/dev/null 2>&1; }
elif command -v shasum >/dev/null 2>&1; then
  sha_check() { shasum -a 256 -c "$1" >/dev/null 2>&1; }
else
  err "need sha256sum or shasum to verify the download"
fi

need curl

# Resolve version (explicit override, else the published "latest" pointer).
version="${KLOVIUS_VERSION:-}"
[ -n "$version" ] || version="$(curl -fsSL "${DL_BASE}/stable.txt")" || err "could not resolve latest version"
# Strip any surrounding whitespace (incl. a stray CRLF) so the URL stays clean.
version="$(printf '%s' "$version" | tr -d '[:space:]')"
[ -n "$version" ] || err "empty version"

tarball="${BIN}-${version}-${target}.tar.gz"
url="${DL_BASE}/releases/${version}/${tarball}"

if [ "${KLOVIUS_DRY_RUN:-}" = "1" ]; then
  echo "target=${target} version=${version}"
  echo "url=${url}"
  exit 0
fi

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

echo "Downloading klovius ${version} (${target})…"
curl -fsSL "$url" -o "${tmp}/${tarball}" || err "download failed: $url"
curl -fsSL "${DL_BASE}/releases/${version}/SHA256SUMS" -o "${tmp}/SHA256SUMS" || err "could not fetch SHA256SUMS"

# Verify only our file's checksum.
( cd "$tmp" && grep " ${tarball}\$" SHA256SUMS > ours.sum && sha_check ours.sum ) \
  || err "checksum verification failed for ${tarball}"

tar -C "$tmp" -xzf "${tmp}/${tarball}" || err "extract failed"
[ -f "${tmp}/${BIN}" ] || err "archive did not contain ${BIN}"
chmod +x "${tmp}/${BIN}"

# Choose an install dir we can actually write to.
if [ -w /usr/local/bin ] 2>/dev/null; then
  dest="/usr/local/bin"
elif command -v sudo >/dev/null 2>&1 && [ -t 0 ]; then
  dest="/usr/local/bin"; SUDO="sudo"
else
  dest="${HOME}/.local/bin"; mkdir -p "$dest"
fi

${SUDO:-} mv "${tmp}/${BIN}" "${dest}/${BIN}" || err "could not install to ${dest}"
echo "Installed klovius to ${dest}/${BIN}"

case ":${PATH}:" in
  *":${dest}:"*) : ;;
  *) echo "Note: ${dest} is not on your PATH. Add it, e.g.:";
     echo "  echo 'export PATH=\"${dest}:\$PATH\"' >> ~/.profile && . ~/.profile" ;;
esac

echo
echo "Next:  klovius login   then   klovius up"
