#!/bin/bash
set -e

if [[ $# != 1 ]]; then
    echo "usage: $0 <install_location>"
    exit 1
fi
install_path=$1

if [[ -x $install_path ]]; then
    if [[ ! -x $install_path/bin/conda ]]; then
        echo "error: $install_path already exists and is not a conda environment"
        exit 1
    else
        env_exists=1
    fi
fi

if [[ -z "$env_exists" ]]; then

    if [[ $(uname) == Linux ]]; then
        platform=Linux
    elif [[ $(uname) == Darwin ]]; then
        platform=MacOSX
    else
        echo "error: only Linux and Mac OS X are supported"
        exit 1
    fi

    miniconda_installer=Miniconda2-latest-$platform-x86_64.sh
    curl -O https://repo.continuum.io/miniconda/$miniconda_installer
    bash $miniconda_installer -b -p $install_path || ( rm $miniconda_installer && false )
    rm $miniconda_installer
fi

touch $install_path/.condarc.collopak
export CONDARC=$install_path/.collopak.condarc
$install_path/bin/conda install \
    --prefix $install_path --channel ${COLLOPAK_CHANNEL:-greg9q} --yes collopak

