#!/bin/sh
#
# otopi -- plugable installer
#

ENV="/etc/otopi.env.d"
for f in $([ -d "${ENV}" ] && find "${ENV}" -name '*.env' | sort); do
	[ -r "${f}" ] && . "${f}"
done

script="$0"
scriptdir="$(dirname "${script}")"
extraenv=""

# in source tree execution
if [ -f "${scriptdir}/.source" ]; then
	export OTOPI_INSOURCETREE=1
	# make sure we are first
	export PYTHONPATH="$(cd "${scriptdir}" && pwd)/..:${PYTHONPATH}"
	extraenv="\"BASE/pluginPath=str:${scriptdir}/../plugins\""
	. ${scriptdir}/../../build/otopi-functions
fi

if [ -f "${scriptdir}/.bundled" ]; then
	export OTOPI_BUNDLED="${scriptdir}"
	# make sure we are first
	export PYTHONPATH="${scriptdir}/pythonlib:${PYTHONPATH}"
	extraenv="\"BASE/pluginPath=str:${scriptdir}/otopi-plugins\""
	. ${scriptdir}/otopi-functions
fi

if [ -z "${OTOPI_BUNDLED}" -a -z "${OTOPI_INSOURCETREE}" ]; then
	. /usr/share/otopi/otopi-functions
fi

if [ -z "${OTOPI_NONROOT}" -a "$(id -u)" != 0 ]; then
	sudo="$(find_util sudo)"
	[ -z "${sudo}" ] && die "Non root execution and no sudo"
	exec "${sudo}" -n \
		/bin/sh -c \
		"'$0' '$*'"
	die "Internal error (sudo)"
fi

OTOPI_PYTHON="${OTOPI_PYTHON:-$(get_otopi_python)}"

[ -z "${OTOPI_PYTHON}" ] && die "Python is required but missing"

pythonver() {
	local v="$1"
	echo "$(($v/1000)).$(($v%1000))"
}
PYTHON_VERSION_MIN="2006"
PYTHON_VERSION="$("${OTOPI_PYTHON}" -c "import sys; print(sys.version_info[0]*1000 + sys.version_info[1])")" || \
	die "Cannot query python version"
[ "${PYTHON_VERSION}" -ge "${PYTHON_VERSION_MIN}" ] || \
	die "Python version $(pythonver ${PYTHON_VERSION}) is too old, expecting at least $(pythonver ${PYTHON_VERSION_MIN})"

# TODO remove '.__main__' when python-2.6 gone
exec "${OTOPI_PYTHON}" -B -m otopi.__main__ "${extraenv} $*"
