#!/usr/bin/env bash
# Global npm entry: self-update via relay version-policy, then node dist/index.js
set -euo pipefail

# npm global: $0 is often /opt/homebrew/bin/cursorconnect (symlink), not …/cursorconnect/bin/
resolve_script_dir() {
  local source="$1"
  while [[ -L "$source" ]]; do
    local link_dir
    link_dir="$(cd -P "$(dirname "$source")" && pwd)"
    source="$(readlink "$source")"
    [[ "$source" != /* ]] && source="$link_dir/$source"
  done
  cd -P "$(dirname "$source")" && pwd
}

BIN_DIR="$(resolve_script_dir "$0")"
ROOT="$(cd "$BIN_DIR/.." && pwd)"
export PATH="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:${PATH:-}"

PRE_EXIT=0
node "$BIN_DIR/pre-start-update.mjs" || PRE_EXIT=$?

if [[ "$PRE_EXIT" -eq 10 ]]; then
  export CURSORCONNECT_UPDATE_ATTEMPTED=1
  exec "$(command -v cursorconnect)" "$@"
fi

if [[ "$PRE_EXIT" -ne 0 ]]; then
  exit "$PRE_EXIT"
fi

exec node "$ROOT/dist/index.js" "$@"
