#!/bin/bash

# install pyenv?

echo "
              #  #   ##   #  #  ###    ##   ###   #### 
              # #   #  #  ####  #  #  #  #  #  #  #    
              ##    #  #  ####  ###   #  #  #  #  ###  
              # #   #  #  #  #  # #   ####  #  #  #    
              #  #   ##   #  #  #  #  #  #  ###   #### 


installing...

"            

echo '
1) setting up folder...

'
# install dir?
echo "Where should komrade live on your device?"
path_komrade_default="`realpath ~/komrade`"
read -p "[$path_komrade_default] " path_komrade
if [ -z "$path_komrade" ]
then
    path_komrade=$path_komrade_default
fi
if [ ! -d "$path_komrade" ]
then
    mkdir -p $path_komrade
    echo "created $path_komrade"
fi



echo '

2) downloading Komrade...

'

path_repo="$path_komrade/code"
if command -v git &> /dev/null
then
    echo "using git..."
    if [ -d "$path_repo" ]
    then 
        cd $path_repo
        git pull
    else
        cd $path_komrade
        
        echo "Use HTTPS or SSH for git?"
        read -p "[HTPS/ssh] " git_method
        
        if [ "$git_method" = "ssh" ]
        then
            echo "using ssh..."
            git clone git@github.com:Komrade/Komrade.git
        else
            git clone https://github.com/Komrade/Komrade.git
        fi
        mv Komrade code
    fi
else
    cd $path_komrade
    curl -LO https://github.com/Komrade/Komrade/archive/master.zip
    unzip master.zip
    rm master.zip
    cp -rT Komrade-master code
    rm -r Komrade-master
fi
cd $path_komrade



echo '

3) setting up python...

'

# if ! command -v pyenv &> /dev/null
if [ ! -d "$HOME/.pyenv" ]
then
    echo "pyenv not installed. install?"
    read -p "[Y/n] " pyenv_yn

    if [ "$pyenv_yn" = "n" ]; then
        echo "Not installing pyenv."
    else
        export PYENV_ROOT="$HOME/.pyenv"
        export PATH="$PYENV_ROOT/bin:$PATH"

        echo "installing..."
        curl https://pyenv.run | bash
        
        echo "installing python 3.7.3..."
        
        
        #eval "$(pyenv init -)"
        
        pyenv install 3.7.3
        pyenv local 3.7.3

    fi
fi



cd $path_komrade
echo '

4) creating virtual environment...

'

## the pyenv way
if command -v pyenv &> /dev/null
then
    cd $path_repo
    pyenv install --skip-existing
    #VENV="${PWD##*/}.venv"
    VENV="venv"
    VENV=${VENV#-}
    python -m venv $VENV
    . $VENV/bin/activate
    python -m pip install -U pip setuptools wheel
    python -m pip install -r requirements.txt

else
    cd $path_repo
    python -m pip install virtualenv
    python -m virtualenv venv
    source venv/bin/activate
    pip install -r requirements.txt
fi

export PATH="$path_repo/bin:$PATH"




echo '

5) adding komrade bin folder to path

'

echo "

# komrade
export PATH=\"$path_repo/bin:\$PATH\"

" >> ~/.bashrc