#!/bin/sh
# Sariphi CLI installer  --  curl -fsSL https://sariphi.ai/sariphi.sh | sh
#
# Installs Bun (if missing) and the `sariphi` command (public edition:
# `sariphi startup-idea evaluate "<idea>"`). Re-running updates it.
set -eu

URL="${SARIPHI_URL:-https://sariphi.ai/sariphi.mjs}"
HOME_DIR="$HOME/.sariphi"
BIN_DIR="${SARIPHI_BIN_DIR:-$HOME/.local/bin}"
MARK="# sariphi-public-wrapper"

say() { printf '%s\n' "$*"; }

# Do not shadow a different `sariphi` (for example the internal build).
existing="$(command -v sariphi 2>/dev/null || true)"
if [ -n "$existing" ] && ! grep -qF "$MARK" "$existing" 2>/dev/null; then
  say "error: another 'sariphi' is already on PATH ($existing); not overwriting it." >&2
  say "Set SARIPHI_BIN_DIR to a directory that comes first on PATH, or remove it." >&2
  exit 1
fi

if ! command -v bun >/dev/null 2>&1 && [ ! -x "$HOME/.bun/bin/bun" ]; then
  say "Bun not found - installing it from https://bun.sh ..."
  curl -fsSL https://bun.sh/install | bash
fi
BUN="$(command -v bun 2>/dev/null || printf '%s' "$HOME/.bun/bin/bun")"

mkdir -p "$HOME_DIR" "$BIN_DIR"
curl -fsSL "$URL" -o "$HOME_DIR/sariphi.mjs.tmp"
mv "$HOME_DIR/sariphi.mjs.tmp" "$HOME_DIR/sariphi.mjs"

# The wrapper pins the Bun path found now, so it works without Bun on PATH.
printf '#!/bin/sh\n%s\nexec "%s" "%s" "$@"\n' "$MARK" "$BUN" "$HOME_DIR/sariphi.mjs" > "$BIN_DIR/sariphi"
chmod +x "$BIN_DIR/sariphi"

say "Installed: $BIN_DIR/sariphi"
case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *) say "Add it to PATH:  export PATH=\"$BIN_DIR:\$PATH\"" ;;
esac
say ""
say "Try:  sariphi startup-idea evaluate \"your idea\" --role founder"
