#!/usr/bin/env bash
set -euo pipefail

SCRIPT_PATH="${BASH_SOURCE[0]}"
while [[ -L "$SCRIPT_PATH" ]]; do
  SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
  LINK_TARGET="$(readlink "$SCRIPT_PATH")"
  if [[ "$LINK_TARGET" == /* ]]; then
    SCRIPT_PATH="$LINK_TARGET"
  else
    SCRIPT_PATH="$SCRIPT_DIR/$LINK_TARGET"
  fi
done
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

# Allow callers to pin a specific Node binary (e.g. distributions that ship
# their own runtime, agent spawn environments where login-shell rc files
# reset PATH and drop node out of sight). When unset, behave exactly like
# before: resolve `node` via PATH. See openduo/duoduo#50.
NODE_BIN="${DUODUO_NODE_BIN:-node}"

if [[ -f "$ROOT_DIR/dist/release/cli.cjs" ]]; then
  exec "$NODE_BIN" "$ROOT_DIR/dist/release/cli.cjs" "$@"
fi

if [[ -f "$ROOT_DIR/dist/release/cli.js" ]]; then
  exec "$NODE_BIN" "$ROOT_DIR/dist/release/cli.js" "$@"
fi

if [[ -x "$ROOT_DIR/node_modules/.bin/tsx" ]]; then
  exec "$ROOT_DIR/node_modules/.bin/tsx" "$ROOT_DIR/src/cli/main.ts" "$@"
fi

if command -v npx >/dev/null 2>&1; then
  exec npx tsx "$ROOT_DIR/src/cli/main.ts" "$@"
fi

echo "tsx not found. Run npm install first." >&2
exit 1
