#!/bin/sh
set -eu

SELF_DIR=$(CDPATH= cd -- "$(dirname "$0")" && pwd)

if [ -n "${REAL_NPM:-}" ]; then
  :
elif [ -x /usr/local/bin/npm ]; then
  REAL_NPM=/usr/local/bin/npm
elif [ -x /opt/homebrew/bin/npm ]; then
  REAL_NPM=/opt/homebrew/bin/npm
else
  PATH_WITHOUT_SELF=$(printf '%s' "$PATH" | sed "s#${SELF_DIR}:##; s#:${SELF_DIR}##; s#${SELF_DIR}\$##")
  REAL_NPM=$(PATH="$PATH_WITHOUT_SELF" command -v npm)
fi

find_workspace_root() {
  dir="$PWD"

  while [ "$dir" != "/" ]; do
    if [ -f "$dir/package.json" ] && grep -q '"workspaces"' "$dir/package.json"; then
      printf '%s\n' "$dir"
      return 0
    fi
    dir=$(dirname "$dir")
  done

  printf '%s\n' "$PWD"
}

if [ "${1-}" = "config" ] && [ "${2-}" = "get" ] && [ "${3-}" = "registry" ]; then
  exec "$REAL_NPM" --prefix "$(find_workspace_root)" config get registry
fi

exec "$REAL_NPM" "$@"
