#!/bin/sh
# Oluso CLI installer.
# curl -fsSL https://desk.oluso.xyz/install.sh | sh
# https://desk.oluso.xyz/docs/installation
set -eu

REPO_URL="${OLUSO_GIT_URL:-https://origin.cursor.com/git/samolubunmi-eth/oluso.git}"
SRC="${OLUSO_SRC:-$HOME/.local/share/oluso}"
BIN_DIR="${HOME}/.local/bin"
MIN_NODE="22.19.0"
PNPM_VERSION="10.33.4"

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

os="$(uname -s)"
case "$os" in
  Darwin|Linux) ;;
  MINGW*|MSYS*|CYGWIN*)
    die "Oluso supports Windows through WSL. Open your WSL shell and run: curl -fsSL https://desk.oluso.xyz/install.sh | sh"
    ;;
  *)
    die "Unsupported system: $os. Oluso supports macOS, Linux, and Windows via WSL."
    ;;
esac

command -v git >/dev/null 2>&1 || die "git is required. Install git, then run this script again."
command -v node >/dev/null 2>&1 || die "Node.js ${MIN_NODE} or newer is required. Install it from https://nodejs.org and run this script again."
command -v corepack >/dev/null 2>&1 || die "corepack is missing. Install Node.js ${MIN_NODE} or newer, which includes corepack."

node_ok="$(node -p 'const [maj,min,pat]=process.versions.node.split(".").map(Number); (maj>22||(maj===22&&(min>19||(min===19&&pat>=0)))) ? "yes" : "no"')"
if [ "$node_ok" != "yes" ]; then
  die "Node.js $(node -v) is too old. Oluso needs ${MIN_NODE} or newer."
fi

if [ -d "$SRC/.git" ]; then
  say "Updating $SRC"
  git -C "$SRC" pull --ff-only
elif [ -e "$SRC" ]; then
  die "$SRC already exists and is not an Oluso checkout. Move it aside or set OLUSO_SRC."
else
  mkdir -p "$(dirname "$SRC")"
  say "Cloning Oluso into $SRC"
  git clone "$REPO_URL" "$SRC"
fi

cd "$SRC"

if ! command -v pnpm >/dev/null 2>&1; then
  corepack enable || true
  corepack prepare "pnpm@${PNPM_VERSION}" --activate || true
fi

if command -v pnpm >/dev/null 2>&1; then
  pnpm install --frozen-lockfile
else
  corepack pnpm install --frozen-lockfile
fi

mkdir -p "$BIN_DIR"
chmod +x "$SRC/packages/cli/bin/oluso.mjs"
ln -sfn "$SRC/packages/cli/bin/oluso.mjs" "$BIN_DIR/oluso"

say ""
say "Linked the oluso bin to $BIN_DIR/oluso"
"$BIN_DIR/oluso" --version

case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *)
    say ""
    say "Add this to your shell profile, then open a new terminal:"
    say "  export PATH=\"$BIN_DIR:\$PATH\""
    ;;
esac

say ""
say "Hosted desk:"
say "  export OLUSO_API_URL=https://api.oluso.xyz"
say "  oluso login"
say ""
say "Docs: https://desk.oluso.xyz/docs/installation"
