#!/usr/bin/env bash

shopt -s extglob

PYTHONS="`command -v python` /usr/bin/python /usr/bin/python2 /usr/bin/python3"
CURL=`command -v curl`
FETCH=`command -v fetch`

trim()
{
    trimmed=$1
    trimmed="${trimmed#"${trimmed%%[![:space:]]*}"}"   # remove leading whitespace characters
    trimmed="${trimmed%"${trimmed##*[![:space:]]}"}"   # remove trailing whitespace characters
    echo $trimmed
}

usage()
{
    printf "
  Usage:

    ${0} [options]

    options:

      --python    : Python interpreter.

"
}

parse_arguments()
{
    for arg do
        val=`echo "$arg" | sed -e "s;--[^=]*=;;"`
        case "$arg" in
            --python=*) PYTHONS="$val $PYTHONS" ;;
            --help) usage ;;
            *) echo "Can't find the option. :$arg";;
        esac
    done
}

parse_arguments $@

if [[ ! -x $CURL ]] && [[ ! -x $FETCH ]] ; then
    echo "pythonz required curl or fetch. Neigher of them were not found in your path."
    exit 1
fi

for PYTHON in $PYTHONS ; do
    if [[ ! -x $PYTHON ]] ; then
        continue
    fi

    PYTHON_VERSION=`$PYTHON -V 2>&1`
    PYTHON_VERSION=${PYTHON_VERSION/"Python "/""}
    PYTHON_VERSION_S=`echo $PYTHON_VERSION | sed -e "s/\(^[[:digit:]]\{1,\}.[[:digit:]]\{1,\}\).*/\1/"`

    if [[ $PYTHON_VERSION_S = "2.6" ]] || [[ $PYTHON_VERSION_S = "2.7" ]] || [[ ${PYTHON_VERSION_S:0:1} = "3" ]] ; then
        PYTHON_FOUND='1'
        break
    fi
done
if [[ $PYTHON_FOUND != '1' ]] ; then
    echo "pythonz requires Python 2.6, 2.7 or higher"
    exit 1
fi

systemwide_install=0
if [[ -n "$PYTHONZ_ROOT" ]] ; then
    ROOT="$PYTHONZ_ROOT"
else
    if (( UID == 0 )) ; then
        systemwide_install=1
        ROOT="/usr/local/pythonz"
    else
        ROOT="$HOME/.pythonz"
    fi
fi
PATH_DISTS="$ROOT/dists"

TEMP_TARBALL="pythonz-latest.tar.gz"
DOWNLOAD_URL="https://github.com/saghul/pythonz/tarball/master"

mkdir -p "$PATH_DISTS"
rm -rf "$PATH_DISTS/pythonz*"

echo "Downloading $DOWNLOAD_URL"
if [[ -x $CURL ]] ; then
    builtin cd $PATH_DISTS ; curl --progress-bar -kL $DOWNLOAD_URL -o "$TEMP_TARBALL"
elif [[ -x $FETCH ]] ; then
    builtin cd $PATH_DISTS ; fetch -o "$TEMP_TARBALL" $DOWNLOAD_URL
fi


echo "Extracting $PATH_DISTS/$TEMP_TARBALL"
builtin cd $PATH_DISTS ; tar zxf $TEMP_TARBALL

TEMP_FILE=`tar -tf $TEMP_TARBALL | head -n1 | sed 's/\///g'`

echo "Installing pythonz into $ROOT"
if (( systemwide_install == 1 )) ; then
    PYTHONZ_ROOT="$ROOT" $PYTHON $PATH_DISTS/$TEMP_FILE/pythonz_install.py --systemwide
else
    $PYTHON $PATH_DISTS/$TEMP_FILE/pythonz_install.py
fi
if [[ $? == 1 ]] ; then
    echo "Failed to install pythonz."
    exit 1
fi