# -*-Shell-script-*-
#
# This file is not a stand-alone shell script; it provides helper functions for
# otopi and otopi-bundle

die() {
	local m="$1"
	echo "***L:ERROR: ${m}"
	exit 1
}

find_util() {
	local util="$1"
	for candidate in \
		"/bin/${util}" \
		"/usr/bin/${util}" \
		"/usr/local/bin/${util}";
	do
		if [ -x "${candidate}" ]; then
			echo "${candidate}"
			break
		fi
	done
}

find_otopi() {
	local pybin=$(find_util "$1")
	if [ -n "${pybin}" ]; then
		${pybin} -c "import pkgutil; print('${pybin}' if pkgutil.find_loader('otopi') else '')"
	fi
}

get_otopi_python() {
	# Allow forcing specific python
	if [ -n "${OTOPI_PYTHON}" ]; then
		echo "${OTOPI_PYTHON}"
		return
	fi

	# Use "python" on EL7
	local anypython=$(find_util python3)
	[ -z "${anypython}" ] && anypython=$(find_util python2)
	[ -z "${anypython}" ] && anypython=$(find_util python)
	[ -z "${anypython}" ] && die "get_otopi_python: Cannot find any python"
	local distribution_name="$(${anypython} -c "import distro; print(distro.linux_distribution(full_distribution_name=0)[0])")"
	local distribution_version="$(${anypython} -c "import distro; print(distro.linux_distribution(full_distribution_name=0)[1].split('.')[0])")"
	if [ \( "${distribution_name}" == "redhat" -o "${distribution_name}" == "centos" \) -a "${distribution_version}" -le "7" ]; then
		echo "python"
		return
	fi

	# Use whatever that has otopi in site-packages, prefer python3
	for p in "python3" "python"
	do
		pyexec=$(find_otopi ${p})
		if [ -n "${pyexec}" ]; then
			echo "${pyexec}"
			break
		fi
	done
}

get_otopi_pythonlib() {
	local pybin=$(get_otopi_python)
	if [ -n "${pybin}" ]; then
		${pybin} -c "import otopi; print(otopi.__path__[0])"
	fi
}
