#!/bin/sh

pythons="$PYTHON2 $PYTHON python2.7 python2.6 python2.4 python2 python3 python"

major_version () {
	_version=$1
	echo ${_version%%.*}
}

minor_version () {
	_version=$1
	_major=$(major_version $_version)
	echo ${_version#${_major}} | cut -d . -f 2
}

match_versions () {
	_required=$1
	_available=$2
	_major_r=$(major_version $_required)
	_minor_r=$(minor_version $_required)
	_major_a=$(major_version $_available)
	_minor_a=$(minor_version $_available)

	# majors do not match
	if [ "$_major_r" != "$_major_a" ]
	then
	  echo 0
	  return
	fi

	# minors do not match
	if [ -n "$_minor_r" -a "$_minor_r" != "$_minor_a" ]
	then
	  echo 0
	  return
	fi

	# versions did match
	echo 1
}

find_python_path () {
	_script=$1
	_version=$2
	_dirname="$(dirname $_script)/../lib"

	for dir in $_dirname/python{$_version,}/site-packages; do
		if [ -d "$dir" ]; then
			echo "$dir"
			return
		fi
	done

	echo "Could not find the python libraries at the expected location. Execution" 1>&2
	echo "will continue, but if errors are found please set PYTHONPATH to include" 1>&2
	echo "the CCTOOLs modules for the python interpreter version $_version." 1>&2
}

if [ -z "$1" ]
then
  echo 'Missing script name or option.' 1>&2
  echo "          To execute a python script: $0 script-name [script options]." 1>&2
  echo "To print the python interpreter path: $0 -n [python versions]." 1>&2
  exit 1
fi

if [ "$1" = "-n" ]
then
	shift
	print_path=1
	required_alternatives="$@"
else
	print_path=0
	script=$(which "$1")
	required_alternatives=$(sed -n '2{s/^#[\t ]*CCTOOLS_PYTHON_VERSION//p;q;}' < $script)
fi

if [ -z "$required_alternatives" ]
then
	echo "No version of python was specified." 1>&2
	exit 1
fi

python=0
version=
for alt in $required_alternatives
do
	for candidate in $pythons
	do
		candidate_full=$(which $candidate 2> /dev/null)
		[ -x $candidate_full ] || continue
		candidate_version=$(${candidate_full} -V 2>&1 | cut -d " " -f 2)

		match=$(match_versions $alt $candidate_version)
		if [ "$match" = 1 ]
		then
			python=$candidate_full
			version=$(major_version $candidate_version).$(minor_version $candidate_version)
			break 2
		fi
	done
done

if [ $python = 0 ]
then
	echo "Could not find a valid python version ($required_alternatives )." 1>&2
	echo 'Please set the environment variables PYTHON or PYTHON2 appropriately.' 1>&2
	exit 1
elif [ $print_path = 1 ]
then
	echo $python
else
	export PYTHONPATH=$(find_python_path $script $version):$PYTHONPATH
	shift
	exec "$python" "$script" "$@"
fi
