#!/usr/bin/env bash
# Wed 17 Aug 2016 13:50:29 CEST

set -e

if [ "${#}" != 3 ]; then
  echo "usage: `basename $0` <basedir> <name> <python-version>"
  echo "example: `basename $0` /opt/conda bob-devel-py34 3.4"
  exit 1
fi

BASEDIR=$1
NAME=$2
PYTHON_VERSION=$3
CONDA=${BASEDIR}/bin/conda

if [ -d ${BASEDIR}/envs/${NAME} ]; then
  ${CONDA} remove -n ${NAME} --all --yes
  if [ -d ${BASEDIR}/envs/${NAME} ]; then
    echo "[>>] Environment ${NAME} survived remove, brute force removing..."
    rm -rf ${BASEDIR}/envs/${NAME}
  fi
fi

if [ "$(uname)" == "Linux" ] && [ ${PYTHON_VERSION} == "2.7" ]; then
    CAFFE=caffe
else
    CAFFE=
fi

# This is needed for toolchain. Since we just use 64-bit, I am not checking if
# the system is 32 bit.
export ARCH=64

# For a complete list of dependencies, please read:
# https://gitlab.idiap.ch/bob/bob/wikis/Dependencies
echo "[>>] Creating environment ${NAME} for python ${PYTHON_VERSION} with bob dependencies..."
${CONDA} create --yes -n ${NAME} \
  --override-channels \
  -c https://www.idiap.ch/software/bob/conda \
  -c defaults \
  python=$PYTHON_VERSION \
  anaconda=4.2.0 \
  boost=1.61 \
  ${CAFFE} \
  cmake \
  coverage \
  cython=0.24.1 \
  dask=0.11.0 \
  docopt \
  ffmpeg=2.8.10 \
  gcc=4.8.5 \
  libgcc=4.8.5 \
  giflib=5.1.4 \
  hdf5=1.8.17 \
  ipython \
  jpeg=8d \
  libblitz=0.10 \
  libmatio=1.5 \
  libpng=1.6.22 \
  libsvm=3.21 \
  libtiff=4.0.6 \
  matplotlib=1.5.3 \
  nose=1.3.7 \
  numexpr=2.6.1 \
  numpy=1.11.1 \
  openblas=0.2.19 \
  opencv=3 \
  pillow=3.3.1 \
  pip=8.1.2 \
  pkg-config \
  psutil=4.3.1 \
  scikit-image=0.12.3 \
  scikit-learn=0.17.1 \
  scipy=0.18.1 \
  sox=14.4.2 \
  sphinx=1.4.6 \
  sphinx_rtd_theme \
  sqlalchemy=1.0.13 \
  tensorflow \
  toolchain \
  virtualenv \
  vlfeat=0.9.20

# remove mkl
${CONDA} install --yes nomkl numpy=1.11.1 scipy=0.18.1 scikit-learn=0.17.1 numexpr=2.6.1
${CONDA} remove --yes mkl mkl-service

echo "[>>] Pip-installing extra dependencies in environment ${NAME} for ${PYTHON_VERSION}..."
source ${BASEDIR}/bin/activate ${NAME}

# Cyvlfeat requires special instructions
cyvlfeat=git+https://github.com/menpo/cyvlfeat@v0.4.5
if [ "$(uname)" == "Linux" ]; then
  CFLAGS="-I${CONDA_PREFIX}/include" LDFLAGS="-L${CONDA_PREFIX}/lib -lvl -Wl,-rpath=${CONDA_PREFIX}/lib" pip --no-cache-dir install ${cyvlfeat}
else
  CFLAGS="-I${CONDA_PREFIX}/include" LDFLAGS="-L${CONDA_PREFIX}/lib -lvl" pip --no-cache-dir install ${cyvlfeat}
fi

pip --no-cache-dir install \
  git+https://github.com/menpo/menpo@v0.7.5 \
  git+https://github.com/menpo/menpofit@v0.4.1 \
  schema \
  pyedflib \
  mne \
  ipdb

echo "[>>] Bye!"
exit 0
