#!/bin/bash

#
# Usage: ./install.sh
#
# Creates a virtual env for the current path, with arcadia symlinks.
# Does not install anything globally (other than pipenv and virtualenv). sudo is not needed.
#

require_tool() {
    X=$(which $1) || {
       >&2 echo "Error: '$1' command line tool is not found"
       return 1
    }
}

find_arcadia() {
    set +x
    pushd . >/dev/null 
    while [ "$PWD" != / ]; do
        [ -f .arcadia.root ] && { echo $PWD; popd > /dev/null; return 0; }
        cd ..
    done
    if [ "$PWD" = / ]; then
        if [ -n "$ARCADIA_ROOT" ]; then
            echo $ARCADIA_ROOT
        else
            >&2 echo -e '\e[91mError: not in Arcadia source root, and ARCADIA_ROOT is not set.\e[0m'
            popd > /dev/null
            return 1 
        fi
    fi
}

install_arcadia_hook() {
    set -e
    pipenv run python -c 'import arcadia' 2>/dev/null && return 0
    ARCADIA_ROOT=$(find_arcadia)
    ${ARCADIA_ROOT}/ya make -j0 --checkout ${ARCADIA_ROOT}/devtools/fleur/imports/arcadia
    pipenv run pip2.7 install --editable "${ARCADIA_ROOT}/devtools/fleur/imports/arcadia"
    pipenv run python -c 'import arcadia'
}

main() {
    require_tool pip || {
        >&2 echo -e "\e[91mCannot proceed. Run 'sudo apt-get install python-pip python-virtualenv' first\\e[91m"
        exit 1
    }

    set -e
    set -x
    pip install --user 'virtualenv>=1.11'
    pip install --user --quiet 'pipenv>=9.0'

    # Create a VEnv (removes existing)
    (pipenv --venv > /dev/null && [ "$1" != "--force" ]) || pipenv --two --site-packages

    # Install arcadia symlinks into the VEnv (if needed)
    install_arcadia_hook

    # Install all packages
    pipenv run pip2.7 install -r requirements.txt

    # checkout arcadia folders
    ya make -j0 --checkout .

    echo -e 'source '"$(pipenv --venv)"'/bin/activate; PATH="$PATH:$HOME/.local/bin"' > ./activate
    set +x
}

set -e
PATH=~/.local/bin:$PATH
main
echo -e '\e[92mEverything is set. Run '"'"'source activate'"'"' to enter VirtualEnv. \e[0m'


