#!/bin/bash
EPREFIX=__EPREFIX__
ACTIVE_VERSION=$(grep -r -e "#define NODE_MAJOR_VERSION" \
	"${EPREFIX}/usr/include/node/node_version.h" \
	| cut -f 3 -d " ")
NODE_VERSION=${NODE_VERSION:-${ACTIVE_VERSION}}

paths=(
	$(find /usr/bin \
		-regextype "posix-extended" \
		-regex "${EPREFIX}/usr/bin/node[0-9]+" \
		| sort -V \
		| tac)
)

found=0
for path in ${paths[@]} ; do
	d=$(dirname "${path}")
	if [[ \
		   -x "${path}" \
		&& -e "${d}/node${NODE_VERSION}" \
		&& "${path}" == "${d}/node${NODE_VERSION}" \
	]] ; then
		"${path}" "${@}"
		found=1
		break
	fi
done

get_installed_versions() {
	for path in ${paths[@]} ; do
		bn=$(basename "${path}")
		bn="${bn/node/}"
		printf "%s " "${bn}"
	done
}

if (( ${found} == 0 )) ; then
echo "Header version:  ${ACTIVE_VERSION}"
echo "Requested version:  ${NODE_VERSION}"
echo "Installed versions:  $(get_installed_versions)"
	exit 1
fi

exit 0
