#!/bin/bash

# Ensure that this script is sourced, not executed
# Note that if the script was executed, we're running inside bash!
# Also note that errors are ignored as `activate foo` doesn't generate a bad
# value for $0 which would cause errors.
if [[ -n $BASH_VERSION ]] && [[ "$(basename "$0" 2> /dev/null)" == "deactivate" ]]; then
    >&2 echo "Error: deactivate must be sourced. Run 'source deactivate'
instead of 'deactivate'.
"
    "$(dirname $0)/conda" ..deactivate -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")
# Provide a symlink-resovled script location
_ABS_SCRIPT_LOCATION=$_SCRIPT_LOCATION
while [ -h "$_ABS_SCRIPT_LOCATION" ]; do
    _DIR="$( cd -P "$(dirname $_ABS_SCRIPT_LOCATION)" && pwd )"
    _ABS_SCRIPT_LOCATION="$(readlink "$_ABS_SCRIPT_LOCATION")"
    [[ $_ABS_SCRIPT_LOCATION != /* ]] && _ABS_SCRIPT_LOCATION="$_DIR/$_ABS_SCRIPT_LOCATION"
done

# Load common functions
get_dirname() {
    echo "$(cd "$(dirname "$1")" && pwd)"
}

run_scripts() {
    _PREFIX="$(echo $(echo $PATH | awk -F ':' '{print $1}')/..)"
    _CONDA_D="${_PREFIX}/etc/conda/$1.d"
    if [[ -d $_CONDA_D ]]; then
        for f in $(find $_CONDA_D -name "*.sh"); do source $f; done
    fi
}

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

run_scripts "deactivate"

_NEW_PATH=$("$_THIS_DIR/conda" ..activateroot "$@")
if (( $? == 0 )); then
    export PATH=$_NEW_PATH
    unset CONDA_DEFAULT_ENV
    unset CONDA_ENV_PATH
    if (( $($_THIS_DIR/conda ..changeps1) )); then
        PS1=$CONDA_OLD_PS1
        unset CONDA_OLD_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
