#!/bin/bash
# wrap-python
#
# Create a shell wrapper around a python script that will pick some installation of python to run it with

if [[ $1 = -h* || $1 = --h* ]]; then
    echo "Usage: wrap-python [<input file>] [<output file>]"
    exit 0
fi

infile=$1
outfile=$2

if [[ $infile ]]; then
    exec -- <"$infile"
fi
if [[ $outfile ]]; then
    exec -- >"$outfile"
fi
cat <<'_END'
#!/bin/sh
set_python () {
    if [ "X$1" != X ] && "$1" -c "import sys;sys.exit(0)" >/dev/null 2>&1; then
        python=$1
        return 0
    else
        return 1
    fi
}

set_python "$python" ||
set_python python ||
set_python python3 ||
set_python pypy3 ||
set_python python2 ||
set_python pypy2 ||
set_python /usr/libexec/platform-python ||
{
    echo >&2 "Can't find working Python"
    exit 128
}

"$python" - "$@" <<'__TLDR__'
_END
cat
echo '__TLDR__'

