#!/usr/bin/env sh

cmd="$1"

sourced=0
if [ -n "$ZSH_EVAL_CONTEXT" ]; then
    case $ZSH_EVAL_CONTEXT in *:file) sourced=1;; esac
elif [ -n "$KSH_VERSION" ]; then
    [ "$(cd $(dirname -- $0) && pwd -P)/$(basename -- $0)" != "$(cd $(dirname -- ${.sh.file}) && pwd -P)/$(basename -- ${.sh.file})" ] && sourced=1
elif [ -n "$BASH_VERSION" ]; then
    (return 0 2>/dev/null) && sourced=1
fi

if [ "$cmd" = activate ] || [ "$cmd" = deactivate ]; then
    if [ "$sourced" -eq 0 ]; then
        echo "$cmd command must be called using 'source' with a supported shell"
        exit 1
    fi
else
    if [ "$sourced" -eq 1 ]; then
        echo "source this script only with activate/deactivate commands"
        return 1
    fi
fi

python=${PYDOCKENV_INTERPRETER:-python}

pydockenv_entry_point=$($python -c 'from pydockenv import cli; print(cli.__file__)')
$python $pydockenv_entry_point $@

exitCode=$?
if [ $exitCode -eq 0 ]
then
    if [ "$cmd" = "activate" ]
    then
        export PYDOCKENV=$2
        export PS1="($PYDOCKENV) $PS1"
    elif [ "$cmd" = "deactivate" ]
    then
        export PS1="${PS1/\($PYDOCKENV\) /}"
        export PYDOCKENV=""
    fi
fi

if [ -n "$PYDOCKENV_DEBUG" ]
then
    env 1>&2
fi

if ! [ $sourced -eq 1 ]; then
    exit $exitCode
fi
