#!/bin/sh
# $0 is whatever shim or symlink `pnpx` was launched through, so walk to the
# file itself before looking beside it. The hop cap matches the kernel's ELOOP
# limit, so a cycle cannot hang the script. Directories come from `${self%/*}`
# and `readlink` runs through `command -p`, so the caller's PATH decides nothing here.
#
# A helper the default path lacks, as in a Nix build sandbox, comes from PATH
# instead, with node_modules and relative entries dropped from it.
caller_path_set=${PATH+set}
caller_path=${PATH-}
helper_path=
rest=$caller_path:
while [ -n "$rest" ]; do
  dir=${rest%%:*}
  rest=${rest#*:}
  case "$dir" in
    */node_modules/*|*/node_modules) ;;
    /*) helper_path=${helper_path:+$helper_path:}$dir ;;
  esac
done
# An empty PATH searches the current directory.
PATH=${helper_path:-/}
# A helper comes from PATH only when the default path lacks it and PATH has it.
# The bash 3.2 that macOS ships as sh answers `command -p -v` from PATH.
run_helper() {
  if command -p -v "$1" >/dev/null 2>&1 || ! command -v "$1" >/dev/null 2>&1; then command -p "$@"; else command "$@"; fi
}
self=$0
# MSYS and Cygwin can launch this with a native Windows path, which has no slash
# for `${self%/*}` to strip. Only a drive letter or a UNC prefix marks one; a
# backslash anywhere else is an ordinary character in a Unix file name, so the
# path is left alone. The separators are swapped in the shell rather than through
# `echo`, which mangles a `\t` or `\b` in a path under dash.
case $self in
  [A-Za-z]:\\*|\\\\*)
    while :; do
      case $self in
        *\\*) self=${self%%\\*}/${self#*\\} ;;
        *) break ;;
      esac
    done
    ;;
esac
# `${self%/*}` needs a slash to strip. A bare name came from a PATH lookup and
# stands for a file in the current directory.
case $self in
  */*) ;;
  *) self=./$self ;;
esac
hops=0
while [ -L "$self" ] && [ "$hops" -lt 40 ]; do
  hops=$((hops + 1))
  link=$(run_helper readlink "$self")
  case $link in
    /*) self=$link ;;
    *) self=${self%/*}/$link ;;
  esac
done
if [ -n "$caller_path_set" ]; then PATH=$caller_path; else unset PATH; fi

# The walk has to end at a regular file. Running out of hops leaves $self a
# symlink; a chain that changed under us can leave it dangling or a directory, and
# a failed readlink leaves a trailing slash. Each case would take `pnpm` from the
# wrong directory — the substitution this script exists to prevent.
if [ -L "$self" ] || [ ! -f "$self" ]; then
  echo "pnpx: could not resolve $0 to a regular file within 40 symlink hops." >&2
  exit 1
fi

pnpm=${self%/*}/pnpm
# The placeholder setup.js replaces with the native binary is not executable, so
# this reports the skipped install script rather than an EACCES from `exec`.
if [ ! -x "$pnpm" ]; then
  echo "pnpx: pnpm's native binary was not installed next to this script." >&2
  echo "Reinstall @pnpm/exe with its install scripts allowed." >&2
  exit 1
fi

exec "$pnpm" dlx "$@"
