# Title: .bash_profile
# Author: Frédéric CHEVALIER <f15.chevalier@gmail.com>
# Version: 3.3
# Created in: 2012-05-25
# Modified in: 2024-12-16


#==========#
# Versions #
#==========#

# v3.3 - 2024-12-16: switch from miniconda to miniforge
# v3.2 - 2022-09-10: add timeout on welcome message
# v3.1 - 2021-05-19: updates related to severs and SGE config changes (e.g., queue) / new env variable added
# v3.0 - 2020-03-01: Linuxbrew added / Miniconda added / some Python env variables removed / R env variables removed / PATH setup improved / misc updates
# v2.3 - 2019-03-10: alias updated / R hack for medusa2 added / no ssh key usage or storage for heron
# v2.2 - 2017-04-23: server name updated / SSH connection through screen improved / welcome message improved
# v2.1 - 2016-07-25: bug about space corrected / exit if not interactive (due to Grid Engine)
# v2.0 - 2016-06-12: PATH setup improved / start_agent with multikey management / start_agent calling improved / screen behaviour added / welcome message improved / alias updated
# v1.10 - 2015-08-17: Python lib adapted to the current version of Python / Consed env variable added / plocate updated to handle several db / pypm alias added / library path updated
# v1.9 - 2015-04-20: Python env variable added / alias updated
# v1.8 - 2014-12-02: proxy-display added (resolve $DISPLAY problem with screen)
# v1.7 - 2014-10-22: alias added / conditional modification of PATH and LD_LIBRARY_PATH to be able to use eog and evince on other server (crow, ...)
# v1.6 - 2014-10-15: alias added / LC* added / LS_COLORS removed / PATH updated / LD_LIBRARY_PATH updated
# v1.5 - 2014-09-30: improve screen session detection to print welcome message at server connection even if screen session is running elsewhere
# v1.4 - 2014-08-14: adapt behavior of the start screen regarding the screen program
# v1.3 - 2014-08-06: part for SSH environment setup moved from .bashrc to avoid setting up SSH environment when connection to a node (qrsh)
# v1.2 - 2014-07-09: behaviour modified when login to a node using qrsh (qrsh alias modified / if loop correction for message)
# v1.1 - 2014-07-01: specific aliases needed for GridEngine added
# v1.0 - 2014-06-28: rewriting for better interplay with .bashrc
# v0.0 - 2012-05-25: creation



#===============================#
# Get the aliases and functions #
#===============================#

# If not running interactively, don't do anything
## Required because Grid Engine runs any shell as login shell by default leading to unwanted messages in the job status
[[ -z "$PS1" ]] && return

# Load bashrc file
[[ -f ~/.bashrc ]] && source ~/.bashrc



#==================#
# Specific aliases #
#==================#

alias pqsub='qsub -V -cwd -o $HOME/status -j y -r y -S /bin/bash'
alias pqsubR='qsub -V -cwd -o $HOME/status -j y -r y -S $(which Rscript)'
alias pqrsh='qrsh -V -cwd -q interactive.q -pty y bash -li'
alias plocate='locate -d "$mlocate_db"'
alias xterm='xterm -bg black -fg white -rightbar -geometry 200x35'

[[ $HOSTNAME =~ heron* ]] && alias ssh="ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no"
alias zeus='ssh zeus'
alias mendel='ssh mendel'
alias crow='ssh crow'
alias bulmer='ssh bulmer'

alias pypm="pypm -g"    # Default parameter for pypm which is a package manager for python
alias model_script_sh='cp $HOME/Templates/script.sh $1'



#================================================#
# User specific environment and startup programs #
#================================================#

#--------#
# Locale #
#--------#

# Get with locale command
export LANG=en_US.UTF-8
export LC_CTYPE=en_US.UTF-8
export LC_TIME=en_US.UTF-8      # Fix timestamp to english format (french connection problem)
export LC_NUMERIC=en_US.UTF-8   # To always have . as decimal separator
export LC_NAME=en_US.UTF-8
LC_ALL=

bind 'set show-all-if-unmodified off'

#-------#
# Paths #
#-------#

# Package config
export PKG_CONFIG_PATH=$(/usr/bin/pkg-config --variable pc_path pkg-config)

# Path variable
[[ $SHLVL -eq 1 ]] && export PATH=$HOME/local/bin:$HOME/local/share:$HOME/local/usr/local/bin:${PATH:+:$PATH}     # Personal path

# Linuxbrew
[[ $SHLVL -eq 1 && -d "$HOME/.linuxbrew" ]] && eval $("$HOME/.linuxbrew/bin/brew" shellenv)

# Use of personal /lib* if recent OS
# Location of bamtools lib (source: http://www.vcru.wisc.edu/simonlab/bioinformatics/programs/install/bamtools.htm)
export LD_LIBRARY_PATH="${LD_LIBRARY_PATH:+$LD_LIBRARY_PATH:}$HOME/local/lib:$HOME/local/lib64"

# Perl
export PERL5LIB=~/local/lib/perl5/site_perl/5.18.2/x86_64-linux/auto:~/local/lib/perl5/5.18.2:~/local/lib/perl5/site_perl:~/local/lib/perl5/site_perl/5.18.2:~/local/lib/perl5/site_perl/5.18.2/x86_64-linux:~/local/lib/perl5/5.18.2/x86_64-linux:/usr/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi:/usr/lib/perl5/site_perl/5.8.8:/usr/lib/perl5/site_perl:/usr/lib64/perl5/vendor_perl/5.8.8/x86_64-linux-thread-multi:/usr/lib/perl5/vendor_perl/5.8.8:/usr/lib/perl5/vendor_perl:/usr/lib64/perl5/5.8.8/x86_64-linux-thread-multi:/usr/lib/perl5/5.8.8

# Python
export PYTHONIOENCODING=utf-8


#----------#
# Programs #
#----------#

# Locate
export mlocate_db=$(ls -1 "$HOME/.mlocate.db"* | tr "\n" ":")

# Consed
export CONSED_HOME=~/local/bin/consed.d

# Vim
export VIMHOME=$HOME/.vim

# Miniforge
[[ -d "$HOME/.miniforge3" ]] && source "$HOME/.miniforge3/etc/profile.d/conda.sh"
[[ -n $CONDA_DEFAULT_ENV ]]  && conda activate $CONDA_DEFAULT_ENV

# OPAM completion
[[ $SHLVL -eq 1 ]] && source $HOME/.opam/opam-init/init.sh > /dev/null 2> /dev/null || true

# Git completion
[[ -s "/etc/bash_completion.d/git" ]] && source /etc/bash_completion.d/git

# Biom completion
[[ $(which biom &> /dev/null ; echo $?) == 0 ]] && eval "$(_BIOM_COMPLETE=source biom)"

# Linuxbrew completion
[[ -s "$HOME/.linuxbrew/etc/bash_completion.d/brew" ]] && source "$HOME/.linuxbrew/etc/bash_completion.d/brew"


# SSH environment setup
SSH_KEY_LIST="$HOME/.ssh/key_list"  # File with full path of keys (one per line) to load with start_agent
[[ -f "$SSH_KEY_LIST" ]] && SSH_KEYS=($(cat $SSH_KEY_LIST))
#lifetime="-t 259200" # seconds => 3 days

if [[ ! ($HOSTNAME =~ heron* || $HOSTNAME =~ compute.*) ]]
then
    if [[ -n "$SSH_CONNECTION" ]]
    then
        # Source SSH settings, if applicable
        # Loading keys
        if [[ -f "${SSH_ENV}" ]]
        then
            source "$SSH_ENV"
            # Check if the ssh key is still stored
            if [[ $(ssh-add -l &> /dev/null; echo $?) != 0 ]]
            then
                pkill -u $USER ssh-agent
                eval start_agent $lifetime ${SSH_KEYS[@]}
            fi
        else
            eval start_agent $lifetime ${SSH_KEYS[@]}
        fi
    fi
fi

# Display forwarding
# dependency: proxy-dsiplay
if [[ ! ($HOSTNAME =~ heron* || $HOSTNAME =~ zeus* || $HOSTNAME =~ compute.*) && -n "$DISPLAY" && $(which proxy-display &> /dev/null; echo $?) == 0 ]]
then
    proxy-display :99
fi

# Improvement of screen usage (prevent screen session withing screen session)
if [[ -n $STY || -n $LC_STY ]]
then
    # Create a screen variable with level of screen
    if [[ -z $LC_STY ]]
    then
        export LC_STY=1
    fi

    # ssh function to change the behaviour of ssh
    function ssh {
        /usr/bin/ssh -t $@ "export LC_STY=$(($LC_STY + 1)) && cd \"$PWD\" && exec $SHELL -l"
    }

    # Alias updated
    for i in $(alias | grep "screen" | cut -d " " -f 2 | cut -d "=" -f 1)
    do
        eval "alias $i=\"echo You are already in a screen session.\""
    done

    [[ $LC_STY -gt 1 ]] && function screen { echo -e "This would start a within screen session. This is not recommanded. But if you need it, call $(which screen)." ; }
fi



#=================#
# Welcome message #
#=================#

name=${HOSTNAME%%.*}
nb=$(printf "%${#name}s\n" "" | sed "s/ /=/g")

# Server message
if [[ ! $HOSTNAME =~ compute.* && -z $STY && -z $LC_STY ]]
then
    bash .welcome.msg
fi

# Info on disk space and cores
if [[ ! ($HOSTNAME =~ heron* || $HOSTNAME =~ compute.*) && (-z $LC_STY || $LC_STY != 1) ]]
then
    mydisk="/master"
    dspace=$(timeout 5s df -h 2> /dev/null)
    if [[ -n "$dspace" ]]
    then
        echo ""
        for i in $mydisk
        do
            [[ ! $(grep "$i " <<< "$dspace") ]] && continue
            echo -e "\033[33mSpace available on $i [% Used/Total/Free]:\033[00m $(grep "$i " <<< "$dspace" | awk '{print $5" / "$2" / "$4}' | head -n 1)"
        done
        echo ""
    fi

    if [[ ($name == "zeus") && (-z $LC_STY || $LC_STY != 1) ]]
    then
        cores=$(timeout 5s qstat -g c)
        echo -e "\033[33mCores available:\033[00m\n"
        echo -e "$cores\n"
    fi
fi

unset dspace
