#!/bin/bash
## Functions to setup BDAP user account for bash & git (only if pending).
#
# Call this script with the name of the action-function as arg[1].

set -e

mydir=$(realpath "${0%/*}")
cd "$mydir"
mycmd="${0##*/}"
conda_env_prefix="$mydir/env"
conda_env_prefix_rel="./env"
ipython_startup_ustore_vars="$HOME/.ipython/profile_default/startup/50-ustor-vars.py"

function _mute {
    "${@}" &> /dev/null
}

function _log {
    echo -n "${FUNCNAME[1]}: "
    echo "${@}"
}
function _log2 {
    echo -n "${FUNCNAME[2]}: "
    echo "${@}"
}

function upd20_inputrc {
    if _mute grep -v ':history-search-forward' ~/.inputrc; then
        _log "already ok"
    else
        _log -n "updating..."
        cat >> ~/.inputrc <<- "EOF"
$include /etc/inputrc

## arrow up
"\e[A":history-search-backward
## arrow down
"\e[B":history-search-forward
"\C-x\C-r": re-read-init-file

EOF
        echo "UPDATED"
    fi
}

function upd20_bashrc_git_completions {
    if _mute grep "/usr/share/bash-completion/completions/git" ~/.bashrc ; then
        _log "already ok"
    else
        _log -n "updating..."
        cat >> ~/.bashrc <<- "EOF"

## Enable git completions
source /usr/share/bash-completion/completions/git

EOF
        echo "UPDATED"
    fi
}

function upd20_bashrc_history {
    if _mute grep "PROMPT_COMMAND=\"history -a\"" ~/.bashrc ; then
        _log "already ok"
    else
        _log -n "updating..."
        cat >> ~/.bashrc <<- "EOF"

####
## HISTORY CONTROL:
## (more options may lie above))
##
## Save all lines of a multiple-line command in the same history entry.
shopt -s cmdhist
## Save multi-line commands to the history with embedded newlines.
shopt -s lithist
## Save each and EVERY cmd to history
#  (not to loose it if terminal closed abruptly!)
PROMPT_COMMAND="history -a"
## Don't put duplicate lines or lines starting with space in the history.
## Ignore 1-char cmds
HISTIGNORE=?:?
## Stop BDAP from escaping variables when pressing TAB.
# It removes also some questionable autocompleton "intelligence"...
#  from: https://askubuntu.com/a/1175329/251379
shopt -u progcomp

EOF
        echo "UPDATED"
    fi
}

function upd20_bashrc_ustore_vars {
    if _mute grep "export USTORE=" ~/.bashrc; then
        _log "already ok"
    else
        _log -n "updating..."
        cat >> ~/.bashrc <<- EOF

## BDAP Storage locations
export PSTORE="/eos/jeodpp/data/projects/LEGENT"
export USTORE="/eos/jeodpp/home/users/${USER}"
export UTRANS="/eos/jeodpp/home/users/${USER}/transfer"
export PTRANS="/eos/jeodpp/data/projects/LEGENT/transfer"

EOF
        echo "UPDATED"
    fi
}

function upd20_bash_aliases {
    if _mute grep 'alias lg=' ~/.bash_aliases; then
        _log "already ok"
    else
        _log -n "updating..."
        cat >> ~/.bash_aliases <<- "EOF"

## GIT ALIASES
alias lg='git lg'
alias lgg='git lgg'
alias log='git log'
alias status='git status'
alias show='git show'
alias log='git log'
alias rb='git rebase'
alias rbi='git rebase -i'
alias rba='git rebase --abort'
alias rbc='git rebase --continue'
alias chrp='git cherry-pick'
alias chrpa='git cherry-pick --abort'
alias chrpc='git cherry-pick --continue'
alias chk='git checkout'
alias ch-='git checkout -'
EOF
        echo "UPDATED"
    fi
}

function upd30_git_user {
    if _mute  git config --global --get user.name; then
        _log "user.name already ok"
    else
        _log -n ""
        read -e -p "+++Enter your git AUTHOR-NAME: " inp
        git config --global user.name "inp"
        echo "UPDATED"
    fi

    if _mute  git config --global --get user.email; then
        _log "user.email already ok"
    else
        _log -n ""
        read -e -p "+++Enter your git AUTHOR-EMAIL: " inp
        git config --global user.email "inp"
        _log "UPDATED"
    fi
}

function upd20_git_aliases {
    if _mute  git config --global --get alias.lg; then
        _log "already ok"
    else
        _log -n "updating..."
        git config --global credential.helper store

        git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
        git config --global alias.lgg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --all"
        git config --global alias.log   'log'
        git config --global alias.status 'status'
        git config --global alias.show  'show'
        git config --global alias.log   'log'
        git config --global alias.rb    'rebase'
        git config --global alias.rbi   'rebase -i'
        git config --global alias.rba   'rebase --abort'
        git config --global alias.rbc   'rebase --continue'
        git config --global alias.chrp  'cherry-pick'
        git config --global alias.chrpa 'cherry-pick --abort'
        git config --global alias.chrpc 'cherry-pick --continue'
        git config --global alias.chk   'checkout'
        git config --global alias.ch-   'checkout -'

        _log "UPDATED"
    fi
}

function upd20_ipython_ustore_vars {
    if [ -f "$ipython_startup_ustore_vars" ]; then
        _log "already ok"
    else
        _log -n "updating..."
        mkdir -p  $(dirname "$ipython_startup_ustore_vars")
        cat > "$ipython_startup_ustore_vars" <<- EOF
## BDAP Storage locations
PSTORE="/eos/jeodpp/data/projects/LEGENT"
USTORE="/eos/jeodpp/home/users/${USER}"
UTRANS="/eos/jeodpp/home/users/${USER}/transfer"
PTRANS="/eos/jeodpp/data/projects/LEGENT/transfer"

EOF
        echo "UPDATED"
    fi
}

function upd40_bashrc_conda_init {
    if _mute  grep ">>> conda initialize >>>" ~/.bashrc; then
        _log 'already ok;  delete ">>> conda initialize >>>" section from `~/.bashrc` to re-run.'
    else
        _log -n "updating..."

        # Strict-priority for when using conda-forge, to speedup
        # eg for `conda-bash-completion` package`,
        # see https://conda-forge.org/docs/user/tipsandtricks.html#how-to-fix-it.
        conda config --set channel_priority strict
        # Suggested by BDAP docs:
        # https://jeodpp.jrc.ec.europa.eu/apps/gitlab/for-everyone/documentation/-/wikis/Jeodpp_services/Jeodesk/JEO-Desk-20-user-manual#conda-use-example-creation-of-an-environment-with-python-35-and-numpy-accessible-via-jupyterlab
        conda config --set auto_activate_base False
        # To reduce bash-prompt width, from:
        # https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#id3
        conda config --set env_prompt '({name})'
        # Stop "conda outdated" message (is `conda env update` faster?).
        conda config --set auto_update_conda False

        conda init bash  # Effective only if never used conda before.
        exit 0
    fi
}

## This function must be the 1st to run after all `upd_xxx` actions.
#  The last command of this action, activating conda-env,
#  will fail if not re-logged in after `conda init bash`.
function upd50_create_conda_env {
    if [ -d "$conda_env_prefix" ]; then
        _log -e "already ok: $conda_env_prefix
        Reminder, how to (re-)activate your environment: conda activate $conda_env_prefix_rel"
    else
        _log "should take ~10' to create a conda-env@$conda_env_prefix..."
        conda env create -p "$conda_env_prefix" -f environment.yml

    fi

    ## Setup any conda-env variables:
    #  - make PATH & PYTHONPATH pointing to project-root,
    #    to be able run & import scripts from anywhere.
    if [ -f "$conda_env_prefix/etc/conda/activate.d/uds_vars.sh" ]; then
        _log -e " OVERRIDE env_vars already ok: $conda_env_prefix/etc/conda/activate.d/uds_vars.sh
        Delete this to re-run it to be effective."
    else
        _log "OVERRIDING env_vars..."
        mkdir -p $conda_env_prefix/etc/conda/{,de}activate.d
        cat > $conda_env_prefix/etc/conda/activate.d/uds_vars.sh <<- EOF
#!/bin/sh

export _UDS_OLD_PATH="\$PATH"
export _UDS_OLD_PYTHONPATH="\$PYTHONPATH"
export PATH="$mydir:\$PATH"
export PYTHONPATH="$mydir:\$PYTHONPATH"
EOF
        cat > $conda_env_prefix/etc/conda/deactivate.d/uds_vars.sh <<- EOF
#!/bin/sh

export PATH="\$_UDS_OLD_PATH"
export PYTHONPATH="\$_UDS_OLD_PYTHONPATH"
unset _UDS_OLD_PATH
unset _UDS_OLD_PYTHONPATH
EOF
          _log "ACTIVATE YOUR ENVIRONMENT with: conda activate $conda_env_prefix_rel"
    fi
}

function _list_all_actions {
    declare -F|grep -oE ' [a-zA-Z]\w+$' | sort
}

function all {
    for cmd in $(_list_all_actions); do
        if [ "$cmd" != "${FUNCNAME[0]}" ]; then
            $cmd
        fi
    done
}

if [[ $# -eq 1 && ( "$1" = "-h" || "$1" = "--help" ) ]]; then
    echo -e "$mycmd - actions to setup a BDAP user account.\n"
    echo -e "SYNTAX:\n    $mycmd\n    $mycmd ACTION\nWHERE:\n    ACTION is one of:"
    _list_all_actions
    echo -e '\nWithout any args, it  launches `all` actions, in order.'
    echo -e '\nNOTES:\n    * The `upd30_git_user` action awaits interactively input from the user.'
    echo -e '    * You may have to logout & re-login after `upd40_bashrc_conda_init`,
      for `upd50_create_conda_env` to succeed.'
    echo -e '    * You can repeatedly run this script, until all action succeed.'
elif [[ $# -eq 0 ]]; then
    echo "Running all actions..."
    all
else
    ## execute the asked action.
    echo "Running '${@}' action..."
    "${@}"
fi
