#!/bin/sh
#
# otopi -- plugable installer
# Copyright (C) 2012-2013 Red Hat, Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#

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
}

script="$0"

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

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"
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"
fi

OTOPI_PYTHON="${OTOPI_PYTHON:-$(find_util 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}" -m otopi.__main__ "${extraenv} $*"
