#!/usr/bin/env bash

nv_cmd_default() {
    local env_name=$(nv_get_first_non_opt_value "$@")
    local prompt_enable="yes"
    local start_new_shell="yes"

    # check that env name is not empty
    if [ "$env_name" = "" ]; then
        echo "Please, specify the name of the environment that will be activated."
        return
    fi

    # try to find --same-shell options
    for opt in "$@"
    do
    case $opt in
        --same-shell)
            start_new_shell="no"
            ;;
    esac
    done

    # start new shell (if need)
    if [ "$start_new_shell" = "yes" ]; then
        local curr_shell=$(echo "${SHELL##*/}")
        local TMPFILE=$(mktemp /tmp/envirius-XXXXXX)

        echo "export NV_IN_NEW_SHELL=yes" >> $TMPFILE
        echo "export NV_PATH=\"$NV_PATH\"" >> $TMPFILE
        echo ". \"$NV_PATH\"/nv" >> $TMPFILE
        echo ". ~/.${curr_shell}rc" >> $TMPFILE
        echo "nv activate $@ --same-shell" >> $TMPFILE
        echo "rm -f $TMPFILE" >> $TMPFILE

        case $curr_shell in
            bash)
                # http://stackoverflow.com/a/18756584/716726
                bash --rcfile $TMPFILE
            ;;
            zsh)
                # http://stackoverflow.com/a/22693120/716726
                zsh --rcs $TMPFILE
            ;;
            *)
                echo "This shell doesn't support."
                echo "Please, try again with option '--same-shell'"
        esac
        return
    fi

    # try to find --prompt-* options
    for opt in "$@"
    do
    case $opt in
        --prompt-enable)
            prompt_enable="yes"
            ;;
        --prompt-disable)
            prompt_enable="no"
            ;;
    esac
    done

    # deactivate previusly activated environment
    local current_env=`nv current`
    if [ "$current_env" != "" ]; then
        nv deactivate
    fi

    local env_name_full=$(nv_get_env_full_path $env_name)
    mkdir -p $env_name_full/bin

    NV_USED_ENV=$env_name
    NV_OLD_PATH=$PATH
    export PATH=$env_name_full/bin:$PATH

    if [ "$prompt_enable" = "yes" ]; then
        NV_OLD_PS1="$PS1"
        export PS1="($env_name)$PS1"
    fi

    # source activate for each plugin
    for plug in $(find $env_name_full/bin/ -type f -iname "activate-*" )
    do
        . $plug
    done

    echo "Environment `nv_bold $env_name` activated."
}

nv_cmd_desc() {
    echo "Activate environment (aliases: on, use)"
}

nv_cmd_help() {
    nv_show_usage "[options] <environment-name>"
    nv_show_desc "$(nv_cmd_desc)"
    echo ""
    echo "Options:"
    echo "  --prompt-enable     Change PS1 varibale: add env name into prompt"
    echo "  --prompt-disable    Do not change PS1 varibale (default)"
    echo "  --same-shell        Enable environment in the same shell (otherwise in a new shell)"
}

# /* vim: set filetype=sh : */
