#!/bin/sh
set -eu

BASE_URL="${CLYC_INSTALL_BASE_URL:-https://app.clyc.io}"
INSTALL_DIR="${CLYC_INSTALL_DIR:-$HOME/.local/bin}"
TARGET="$INSTALL_DIR/clyc"

need() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "clyc install: missing required command: $1" >&2
    exit 1
  fi
}

need curl
need node

NODE_MAJOR="$(node -p "process.versions.node.split('.')[0]")"
NODE_MINOR="$(node -p "process.versions.node.split('.')[1]")"
if [ "$NODE_MAJOR" -lt 18 ] || { [ "$NODE_MAJOR" -eq 18 ] && [ "$NODE_MINOR" -lt 18 ]; }; then
  echo "clyc install: Node.js 18.18 or newer is required" >&2
  exit 1
fi

mkdir -p "$INSTALL_DIR"

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

curl -fsSL "$BASE_URL/api/developer/cli/clyc.mjs" -o "$tmp"
chmod 755 "$tmp"
mv "$tmp" "$TARGET"
trap - EXIT

echo "Installed clyc to $TARGET"

case ":$PATH:" in
  *":$INSTALL_DIR:"*) ;;
  *)
    echo "Add $INSTALL_DIR to PATH to run clyc from any shell."
    ;;
esac

"$TARGET" --help >/dev/null
echo "Run: clyc auth login --api-url $BASE_URL --token clyc_..."
