
# Copyright 2015-2023 Rivoreo

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR


which() {
	if [ -n "$BASH" ]; then
		# No support for '-s'
		type -P "$@"
		return
	fi

	local print_all silent
	OPTIND=0
	while getopts as c
	do case $c in
		a)
			print_all=1
			;;
		s)
			silent=1
			;;
		\?)
			echo "Usage: which [-a|-s] <name> ..." 1>&2
			return 255
			;;
	esac done
	if [ $# -lt $OPTIND ]; then
		echo "Usage: which [-a|-s] <name> ..." 1>&2
		return 255
	fi
	[ -n "$silent" ] && print_all=
	shift $((OPTIND-1))
	local r=0 ORIG_IFS="$IFS" found
	which_check_path() {
		if [ -x "$1" ] && [ -f "$1" ]; then
			[ -z "$silent" ] && printf %s\\n "$1"
			true
		else
			false
		fi
	}
	for name in "$@"; do case "$name" in
		*/)
			r=1
			;;
		*/*)
			which_check_path "$name" || r=1
			;;
		*)
			found=
			IFS=:
			for d in $PATH; do
				if [ -n "$d" ]; then
					which_check_path "$d/$name"
				else
					which_check_path "$name"
				fi && found=1 && [ -z "$print_all" ] && break
			done
			IFS="$ORIG_IFS"
			[ -z "$found" ] && r=1
			;;
	esac done
	unset which_check_path
	return $r
}

get_perl_executable_path() {
	local perl
	for k in PERL PERL5 REAL_PERL; do
		eval "perl=\"\$$k\""
		which -- "$perl" && return
	done
	which perl
}

