#!/bin/sh
# backlog-bridge — global command of backlog-bridge. Runs from any directory:
#   backlog-bridge <backlog-bridge command ...>     -> src/cli.ts
#   backlog-bridge sync [flag ...]      -> src/sync.ts
# Finds a recent enough Node by itself (machines may have several via nvm; the default may be too old):
#   $BACKLOG_BRIDGE_NODE > node on PATH > ~/.nvm/versions/node/* > Homebrew.
set -e

# Real path of the script (backlog-bridge is usually invoked via a symlink in ~/.local/bin or npm bin).
self=$0
while [ -L "$self" ]; do
  link=$(readlink "$self")
  case $link in /*) self=$link ;; *) self=$(dirname "$self")/$link ;; esac
done
root=$(cd "$(dirname "$self")/.." && pwd)

# Installed via npm (inside node_modules) -> Node won't run .ts there, use the dist/ build.
case $root in
  */node_modules/*) entry_dir=$root/dist ext=js min="20 11" ;;
  *) entry_dir=$root/src ext=ts min="22 18" ;;
esac

node_ok() {
  "$1" -e 'const [a,b]=process.versions.node.split(".").map(Number),[x,y]=process.argv.slice(1).map(Number);process.exit(a>x||(a===x&&b>=y)?0:1)' $min 2>/dev/null
}

pick_node() {
  for n in "$BACKLOG_BRIDGE_NODE" "$(command -v node 2>/dev/null)"; do
    [ -n "$n" ] && [ -x "$n" ] && node_ok "$n" && { echo "$n"; return; }
  done
  for n in $(ls -d "${NVM_DIR:-$HOME/.nvm}"/versions/node/v*/bin/node 2>/dev/null | sort -t v -k 2 -V -r) \
           /opt/homebrew/bin/node /usr/local/bin/node; do
    [ -x "$n" ] && node_ok "$n" && { echo "$n"; return; }
  done
  return 1
}

node=$(pick_node) || {
  echo "backlog-bridge needs Node.js >= $(echo $min | tr ' ' .) (no recent enough version found)." >&2
  echo "Install with: nvm install 22   — or set BACKLOG_BRIDGE_NODE=/path/to/node" >&2
  exit 1
}

if [ "$1" = "sync" ]; then shift; exec "$node" "$entry_dir/sync.$ext" "$@"; fi
exec "$node" "$entry_dir/cli.$ext" "$@"
