#!/bin/sh
# brod installer — served at https://brod.sh
#   curl -fsSL brod.sh | sh
#
# Read-only by design: this script only downloads and installs the `brod` CLI.
# It never touches a Kafka cluster.
set -eu

REPO="brodsh/brod-cli"          # public, MIT, open-source CLI
BIN="brod"

say()  { printf '\033[0;32m▮\033[0m %s\n' "$1"; }
err()  { printf '\033[0;31m✗\033[0m %s\n' "$1" >&2; exit 1; }

# ── pick a writable install dir — NEVER sudo ──────────────────────
# Order: BROD_INSTALL_DIR → /usr/local/bin if already writable → ~/.local/bin.
choose_dir() {
  if [ -n "${BROD_INSTALL_DIR:-}" ]; then printf '%s' "$BROD_INSTALL_DIR"; return; fi
  if [ -d /usr/local/bin ] && [ -w /usr/local/bin ]; then printf '%s' /usr/local/bin; return; fi
  printf '%s' "${HOME}/.local/bin"
}
INSTALL_DIR="$(choose_dir)"

# ── detect platform ───────────────────────────────────────────────
os="$(uname -s | tr '[:upper:]' '[:lower:]')"
arch="$(uname -m)"
case "$os" in
  linux|darwin) ;;
  *) err "unsupported OS: $os (linux/darwin only)";;
esac
case "$arch" in
  x86_64|amd64) arch="amd64";;
  arm64|aarch64) arch="arm64";;
  *) err "unsupported arch: $arch";;
esac

# ── resolve latest version (override with BROD_VERSION) ───────────
ver="${BROD_VERSION:-}"
if [ -z "$ver" ]; then
  ver="$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" \
        | grep -m1 '"tag_name"' | cut -d '"' -f4 || true)"
fi
[ -n "$ver" ] || err "could not resolve latest release of ${REPO}. Set BROD_VERSION or build from source."

asset="${BIN}_${ver#v}_${os}_${arch}.tar.gz"
url="https://github.com/${REPO}/releases/download/${ver}/${asset}"

say "installing ${BIN} ${ver} (${os}/${arch})"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT

curl -fsSL "$url" -o "$tmp/$asset" || err "download failed: $url"
tar -xzf "$tmp/$asset" -C "$tmp" || err "extract failed"

mkdir -p "$INSTALL_DIR" 2>/dev/null \
  || err "cannot create ${INSTALL_DIR} — set BROD_INSTALL_DIR to a writable dir"
mv "$tmp/$BIN" "$INSTALL_DIR/$BIN" \
  || err "cannot write to ${INSTALL_DIR} — set BROD_INSTALL_DIR to a writable dir"
chmod +x "$INSTALL_DIR/$BIN" 2>/dev/null || true

say "done → ${INSTALL_DIR}/${BIN}"

# If the install dir isn't on PATH, tell the user how to add it (no sudo).
case ":${PATH}:" in
  *":${INSTALL_DIR}:"*) ;;
  *)
    printf '\n  \033[0;33mnote\033[0m  %s is not on your PATH. Add it:\n' "$INSTALL_DIR"
    printf '    echo '\''export PATH="%s:$PATH"'\'' >> ~/.zshrc   # or ~/.bashrc\n' "$INSTALL_DIR"
    printf '    then restart your shell (or run: export PATH="%s:$PATH")\n' "$INSTALL_DIR"
    ;;
esac
printf '\n  try it:  \033[0;32mbrod scan\033[0m\n\n'
