#!/usr/bin/env bash
set -euo pipefail
export CURSOR_INVOKED_AS="$(basename "$0")"
# Get the directory of the actual script (handles symlinks)
if command -v realpath >/dev/null 2>&1; then
  SCRIPT_DIR="$(dirname "$(realpath "$0")")"
else
  SCRIPT_DIR="$(dirname "$(readlink "$0" || echo "$0")")"
fi
NODE_BIN="$SCRIPT_DIR/node"

# Enable Node.js compile cache for faster CLI startup (requires Node.js >= 22.1.0)
# Cache is automatically invalidated when source files change
if [ -z "${NODE_COMPILE_CACHE:-}" ] && [ -n "${HOME:-}" ]; then
  if [[ "${OSTYPE:-}" == darwin* ]]; then
    export NODE_COMPILE_CACHE="$HOME/Library/Caches/cursor-compile-cache"
  else
    export NODE_COMPILE_CACHE="${XDG_CACHE_HOME:-$HOME/.cache}/cursor-compile-cache"
  fi
fi

should_skip_system_ca() {
  case "${AGENT_CLI_CREDENTIAL_STORE:-}" in
    file)
      return 0
      ;;
  esac
  return 1
}

# Node opens its debugger for any process of the same user that sends it
# SIGUSR1. The CLI stops that once it has loaded; --disable-sigusr1 covers the
# time before. The same variable that keeps the CLI inspectable keeps the signal.
NODE_FLAGS="--disable-sigusr1"
case "${CURSOR_AGENT_ALLOW_PROCESS_INSPECTION:-}" in
  1 | true)
    NODE_FLAGS=""
    ;;
esac
if ! should_skip_system_ca; then
  NODE_FLAGS="$NODE_FLAGS --use-system-ca"
fi

# Node exits on a flag it does not know, so try the flags before relying on
# them. NODE_FLAGS is unquoted on purpose: it holds one flag per word.
if [ -n "$NODE_FLAGS" ] && "$NODE_BIN" $NODE_FLAGS --version >/dev/null 2>&1; then
  exec -a "$0" "$NODE_BIN" $NODE_FLAGS "$SCRIPT_DIR/index.js" "$@"
fi

if ! should_skip_system_ca && "$NODE_BIN" --use-system-ca --version >/dev/null 2>&1; then
  exec -a "$0" "$NODE_BIN" --use-system-ca "$SCRIPT_DIR/index.js" "$@"
fi

exec -a "$0" "$NODE_BIN" "$SCRIPT_DIR/index.js" "$@"
