#!/usr/bin/env bash

PYTHON=`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=*) PYTHON="$val" ;;
            --help) usage ;;
            *) echo "Can't find the option. :$arg";;
        esac
    done
}

parse_arguments $@

if [[ ! -x $PYTHON ]] ; then
    echo "Python (2.4, 2.5 or 2.6) is required."
    exit
fi
if [[ ! -x $CURL ]] ; then
    echo "curl is required."
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
    printf "Python's version is $PYTHON_VERSION_S:
  2.4 <= python < 3.0 is required.
"
    exit
fi

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

STABLE_VERSION=`curl -sL 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 -sL $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
