#!/bin/sh
# This file is part of curtin. See LICENSE file for copyright and license info.

PY3OR2_MAIN="curtin"
PY3OR2_MCHECK="curtin.deps.check"
PY3OR2_PYTHONS=${PY3OR2_PYTHONS:-"python3:python"}
PYTHON=${PY3OR2_PYTHON}
PY3OR2_DEBUG=${PY3OR2_DEBUG:-0}

debug() {
   [ "${PY3OR2_DEBUG}" != "0" ] || return 0
   echo "$@" 1>&2
}
fail() { echo "$@" 1>&2; exit 1; }

# if $0 is is bin/ and dirname($0)/../module exists, then prepend PYTHONPATH
mydir=${0%/*}
updir=${mydir%/*}
if [ "${mydir#${updir}/}" = "bin" -a -d "$updir/${PY3OR2_MCHECK%%.*}" ]; then
    updir=$(cd "$mydir/.." && pwd)
    case "$PYTHONPATH" in
        *:$updir:*|$updir:*|*:$updir) :;;
        *) export PYTHONPATH="$updir${PYTHONPATH:+:$PYTHONPATH}"
           debug "adding '$updir' to PYTHONPATH"
            ;;
    esac
fi

if [ ! -n "$PYTHON" ]; then
    first_exe=""
    oifs="$IFS"; IFS=":"
    best=0
    best_exe=""
    [ "${PY3OR2_DEBUG}" = "0" ] && _v="" || _v="-v"
    for p in $PY3OR2_PYTHONS; do
        command -v "$p" >/dev/null 2>&1 ||
            { debug "$p: not in path"; continue; }
        [ -z "$PY3OR2_MCHECK" ] && PYTHON=$p && break
        out=$($p -m "$PY3OR2_MCHECK" $_v -- "$@" 2>&1) && PYTHON="$p" &&
            { debug "$p is good [$p -m $PY3OR2_MCHECK $_v -- $*]"; break; }
        ret=$?
        debug "$p [$ret]: $out"
        # exit code of 1 is unuseable
        [ $ret -eq 1 ] && continue
        [ -n "$first_exe" ] || first_exe="$p"
        # higher non-zero exit values indicate more plausible usability
        [ $best -lt $ret ] && best_exe="$p" && best=$ret &&
            debug "current best: $best_exe"
    done
    IFS="$oifs"
    [ -z "$best_exe" -a -n "$first_exe" ] && best_exe="$first_exe"
    [ -n "$PYTHON" ] || PYTHON="$best_exe"
    [ -n "$PYTHON" ] ||
        fail "no availble python? [PY3OR2_DEBUG=1 for more info]"
fi
debug "executing: $PYTHON -m \"$PY3OR2_MAIN\" $*"
exec $PYTHON -m "$PY3OR2_MAIN" "$@"

# vi: ts=4 expandtab syntax=sh
