#!/bin/bash
if [ -z "$VIRTUAL_ENV" ]; then
    CUR_DIR=$(pwd)
    # search for the next .env
    while [[ "$PWD" != "/" && "$PWD" != "$home" ]]; do
        env_file="$PWD/.env"
        if [[ -f "$env_file" ]]; then
            BASE_DIR=$(dirname $env_file)
            break
        fi
        builtin cd ..
    done

    if [ ! -z "$BASE_DIR" ]; then
        if [ -f "${BASE_DIR}/${PWD##*/}_stakkr/bin/activate" ]; then
            echo "Activating that virtualenv (${PWD##*/}_stakkr)"
            source ${BASE_DIR}/${PWD##*/}_stakkr/bin/activate
            source ${BASE_DIR}/bash_completion
        else
            echo "That environment hasn't been initialized yet, check your venv name (must be ${BASE_DIR}/${PWD##*/})"
            break
        fi
    fi

    cd $CUR_DIR
fi
