#!/usr/bin/env sh
# briven CLI installer — pulls the tarball published as a Codeberg release
# asset and drops a `briven` shim into the user's PATH.
#
# Usage:
#   curl -fsSL https://briven.tech/install | sh
#   curl -fsSL https://briven.tech/install | BRIVEN_CLI_VERSION=0.2.0 sh
#   curl -fsSL https://briven.tech/install | BRIVEN_CLI_PREFIX="$HOME/.local" sh
#
# Requires: curl OR wget; tar; a node runtime (node >=20 OR bun) on PATH.

set -eu

VERSION="${BRIVEN_CLI_VERSION:-0.2.0}"
PREFIX="${BRIVEN_CLI_PREFIX:-$HOME/.local}"
RELEASE_HOST="${BRIVEN_RELEASE_HOST:-https://codeberg.org}"
RELEASE_REPO="${BRIVEN_RELEASE_REPO:-flndrn/briven}"
TARBALL_NAME="briven-cli-${VERSION}.tgz"
TARBALL_URL="${RELEASE_HOST}/${RELEASE_REPO}/releases/download/cli-v${VERSION}/${TARBALL_NAME}"
INSTALL_DIR="${PREFIX}/share/briven-cli"
BIN_DIR="${PREFIX}/bin"
SHIM="${BIN_DIR}/briven"

step() { printf '\033[1;36m▸\033[0m %s\n' "$1"; }
warn() { printf '\033[1;33m!\033[0m %s\n' "$1" >&2; }
fail() { printf '\033[1;31m✗\033[0m %s\n' "$1" >&2; exit 1; }

# ─── Preflight ──────────────────────────────────────────────────────────────

have_runtime=0
if command -v node >/dev/null 2>&1; then
  have_runtime=1
elif command -v bun >/dev/null 2>&1; then
  have_runtime=1
fi
if [ "$have_runtime" -eq 0 ]; then
  fail "node (>=20) or bun is required on PATH. Install one first, then re-run."
fi

if ! command -v tar >/dev/null 2>&1; then
  fail "tar is required."
fi

fetcher=""
if command -v curl >/dev/null 2>&1; then
  fetcher="curl -fsSL"
elif command -v wget >/dev/null 2>&1; then
  fetcher="wget -qO-"
else
  fail "curl or wget required."
fi

# ─── Download ───────────────────────────────────────────────────────────────

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

step "Downloading ${TARBALL_NAME} from Codeberg release cli-v${VERSION}"
if ! $fetcher "$TARBALL_URL" > "$tmp/$TARBALL_NAME"; then
  fail "download failed: $TARBALL_URL"
fi

# Codeberg returns HTML on 404 — confirm we got a real tarball.
if ! tar -tzf "$tmp/$TARBALL_NAME" >/dev/null 2>&1; then
  fail "downloaded file is not a tarball — version cli-v${VERSION} may not have a release asset yet"
fi

# ─── Install ────────────────────────────────────────────────────────────────

mkdir -p "$INSTALL_DIR" "$BIN_DIR"

step "Extracting to $INSTALL_DIR"
# npm-pack tarballs unpack as ./package/* — strip that prefix.
tar -xzf "$tmp/$TARBALL_NAME" -C "$INSTALL_DIR" --strip-components=1

step "Writing shim to $SHIM"
cat > "$SHIM" <<EOF
#!/usr/bin/env sh
# briven CLI shim — generated by installer
exec node "$INSTALL_DIR/bin/briven.js" "\$@"
EOF
chmod +x "$SHIM"

# ─── PATH check ─────────────────────────────────────────────────────────────

if ! echo ":$PATH:" | grep -q ":$BIN_DIR:"; then
  warn "$BIN_DIR is not on your PATH."
  warn "Add it to ~/.zshrc or ~/.bashrc:"
  warn "  export PATH=\"$BIN_DIR:\$PATH\""
fi

printf '\n\033[1;32m✓\033[0m briven %s installed.\n' "$VERSION"
printf '  Run:  \033[1mbriven\033[0m\n\n'
