#!/usr/bin/env bash

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

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 ]] ; then
    echo "pythonbrew required curl. curl was not found in your path."
    exit
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.4" ]] || [[ $PYTHON_VERSION_S = "2.5" ]] || [[ $PYTHON_VERSION_S = "2.6" ]] ; then
		PYTHON_FOUND='1'
		break
	fi
done
if [[ $PYTHON_FOUND != '1' ]] ; then
    echo "pythonbrew required Python (2.4, 2.5 or 2.6)."
    #TODO Installing python.
    exit
fi

ROOT="$HOME/.pythonbrew"
if [[ -n $PYTHONBREW_ROOT ]] ; then
    ROOT=$PYTHONBREW_ROOT
fi
PATH_DISTS="$ROOT/dists"

STABLE_VERSION=`curl -skL https://github.com/utahta/pythonbrew/raw/master/stable-version.txt`
TEMP_FILE="pythonbrew-$STABLE_VERSION"
TEMP_TARBALL="$TEMP_FILE.tar.gz"
DOWNLOAD_URL="http://pypi.python.org/packages/source/p/pythonbrew/$TEMP_TARBALL"

mkdir -p $PATH_DISTS
rm -rf $PATH_DISTS/$TEMP_TARBALL
rm -rf $PATH_DISTS/$TEMP_FILE

echo "Downloading $DOWNLOAD_URL"
builtin cd $PATH_DISTS ; curl --progress-bar -kL $DOWNLOAD_URL -o "$TEMP_TARBALL"

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

echo "Installing pythonbrew into $ROOT"
$PYTHON $PATH_DISTS/$TEMP_FILE/pythonbrew_install.py
if [[ $? == 1 ]] ; then
    echo "Failed to install pythonbrew."
    exit
fi
