#!/usr/bin/env bash
# MIT License © Sindre Sorhus

# If npm_node_execpath is set and exists, prefer that over local node package
if [[ -n $npm_node_execpath && -x $npm_node_execpath ]]; then
	# Don't add local node to PATH when npm_node_execpath is available
	# This ensures consistency with the parent npm process
	:
elif [[ -f "$PWD/node_modules/node/bin/node" ]]; then
	PATH="$PWD/node_modules/node/bin:$PATH"
	export PATH
fi

if [[ -z $RUN_NODE_CACHE_PATH ]]; then
	PATH_CACHE="$HOME"/.node_path
else
	PATH_CACHE="$RUN_NODE_CACHE_PATH"
	if [[ -f "$PATH_CACHE" ]]; then
		. "$PATH_CACHE"
		export PATH
	fi
fi

get_user_path() {
	[[ -x "/usr/libexec/path_helper" ]] && eval $(/usr/libexec/path_helper -s)
	echo "$($SHELL -i -l -c 'echo -e "\n"PATH=\"$PATH:\$PATH\""\n"' 2>/dev/null | grep "^PATH=")" > "$PATH_CACHE"
}

set_path() {
	if [[ -f "$PATH_CACHE" ]]; then
		. "$PATH_CACHE"
	else
		get_user_path
		. "$PATH_CACHE"
	fi

	export PATH
}

has_npx() {
	command -v npx >/dev/null 2>&1
}

if ! has_npx; then
	set_path

	# Retry by deleting old path cache
	if ! has_npx; then
		rm "$PATH_CACHE"
		set_path
	fi
fi

if has_npx; then
	npx "$@"
else
	if [[ -z $RUN_NODE_ERROR_MSG ]]; then
		echo "Couldn't find the npx binary. Ensure you have npm/npx installed. Open an issue on https://github.com/sindresorhus/run-node"
	else
		echo "$RUN_NODE_ERROR_MSG"
	fi
fi