#!/bin/bash

# search Python version and python executable
PYTHON_EXE=`which python2.6` || exit 1

# search virtualenv executable and check its version
for VIRTUALENV_SUFFIX in "-2.7" "-2.6" ""
do
	VIRTUALENV_EXE=`which virtualenv$VIRTUALENV_SUFFIX 2> /dev/null` && break
done

VIRTUALENV_VERSION=$((`$VIRTUALENV_EXE --version | sed 's/^\([0-9]\+\)\.\([0-9]\+\)\..*/\1*1000+\2/'`))
if [ "$VIRTUALENV_VERSION" -ge 1007 ]
then
	VIRTUALENV_OPTS=--system-site-packages
fi

# where are requirements ? (deb and rpm don't use same doc directory)
REQUIREMENTS=`ls -1 /usr/share/doc/polynum*/requirements | sort -r | head -1`

# where to build the virtualenv : /opt/polynum/virtualenv by defaut
VEDIR=${VIRTUAL_ENV-/opt/polynum/virtualenv}

# pip can use a --proxy option
PIPOPT=$PIPOPT" --log=$VEDIR/install.log"
if [ x"$PROXY" != "x" ]; then
  PIPOPT=$PIPOPT" --proxy=$PROXY"
fi

function abort() {
  echo $1 1>&2
  exit 1
}

test -e ${VEDIR}/lib && abort "$VEDIR already exists"

DIR=`dirname $VEDIR`
VE=`basename $VEDIR`
test -d $DIR || "$DIR does not exist (or is not a directory)"

cd $DIR || abort "cannot cd to $DIR"

echo ""
echo "Building PolyNum virtualenv in $VEDIR :"
echo "  $VIRTUALENV_EXE --python=${PYTHON_EXE} $VIRTUALENV_OPTS $VE"
echo ""

$VIRTUALENV_EXE --python=${PYTHON_EXE} $VIRTUALENV_OPTS $VE || abort "cannot create virtualenv $VE in $DIR"

cd $VE
. bin/activate || abort "cannot activate virtualenv (???)"

echo ""
echo "Installing packages with pip (detailed log in $VEDIR/install.log)"
echo ""
pip $PIPOPT install -U pip
pip $PIPOPT install --requirement=$REQUIREMENTS

echo ""
echo -n "Creating .pyc files (compileall) .."
$PYTHON_EXE -m compileall -f -q $VEDIR
echo "..done"

echo ""
echo "PolyNum virtualenv created in $VEDIR"
echo ""
