#!/bin/bash

# Ensure that this script is sourced, not executed
# Note that if the script was executed, we're running inside bash!
if [[ -n $BASH_VERSION ]] && [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
    $(dirname $0)/conda ..activate -h
    exit 1
fi

# Determine the directory containing this script
if [[ -n $BASH_VERSION ]]; then
    _SCRIPT_LOCATION=${BASH_SOURCE[0]}
elif [[ -n $ZSH_VERSION ]]; then
    _SCRIPT_LOCATION=${funcstack[1]}
else
    echo "Only bash and zsh are supported"
    return 1
fi
_THIS_DIR=$(dirname "$_SCRIPT_LOCATION")

# http://stackoverflow.com/a/21188136/161801
get_abs_filename() {
    echo "$(cd "$(dirname "$1")" && pwd)/$(basename "$1")"
}

if [[ -n $CONDA_DEFAULT_ENV ]]; then
    if $_THIS_DIR/conda ..checkenv "$@"; then
        _NEW_PATH=$($_THIS_DIR/conda ..deactivate)
        export PATH=$_NEW_PATH
        if (( $($_THIS_DIR/conda ..changeps1) )); then
            PS1=$CONDA_OLD_PS1
            unset CONDA_OLD_PS1
        fi
    else
        return 1
    fi
fi

_NEW_PATH=$($_THIS_DIR/conda ..activate "$@")
if (( $? == 0 )); then
    export PATH=$_NEW_PATH
    # If the string contains / it's a path
    if [[ "$@" == */* ]]; then
        export CONDA_DEFAULT_ENV=$(get_abs_filename "$@")
    else
        export CONDA_DEFAULT_ENV="$@"
    fi

    if (( $($_THIS_DIR/conda ..changeps1) ));  then
        CONDA_OLD_PS1="$PS1"
        PS1="($CONDA_DEFAULT_ENV)$PS1"
    fi
else
    return $?
fi

if [[ -n $BASH_VERSION ]]; then
    hash -r
elif [[ -n $ZSH_VERSION ]]; then
    rehash
else
    echo "Only bash and zsh are supported"
    return 1
fi
