# Title: .bash_profile
# Author: Frédéric CHEVALIER <f15.chevalier@gmail.com>
# Version: 2.1
# Created in: 2012-05-25
# Modified in: 2016-07-25


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

# 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
if [[ -f ~/.bashrc ]]
then
	source ~/.bashrc
fi



#==================#
# 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 -pty y bash -li'
alias plocate='locate -d "$mlocate_db"'
alias xterm='xterm -bg black -fg white -rightbar -geometry 200x35'

alias medusa='ssh medusa'
alias medusa2='ssh medusa2'
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=


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

# Path variable
export PATH=$HOME/local/bin:$HOME/local/share:$HOME/local/usr/local/bin:$PATH     # Personal path

# Use of personal /lib* if recent OS
if [[ $HOSTNAME != heron* && $(lsb_release -r | cut -f 2) > 6.4 ]]
then
    # Location of bamtools lib (source: http://www.vcru.wisc.edu/simonlab/bioinformatics/programs/install/bamtools.htm)
    export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$HOME/local/lib:$HOME/local/lib64"
fi

# Special paths for medusa and nodes
if [[ $HOSTNAME =~ medusa* || $HOSTNAME =~ compute.* ]]
then
    # System path
    export PATH=$PATH:/opt/openmpi/bin:/opt/bio/ncbi/bin:/opt/bio/mpiblast/bin:/opt/bio/hmmer/bin:/opt/bio/EMBOSS/bin:/opt/bio/clustalw/bin:/opt/bio/tcoffee/bin:/opt/bio/phylip/exe:/opt/bio/mrbayes:/opt/bio/fasta:/opt/bio/glimmer/bin:/opt/bio/glimmer/scripts:/opt/bio/gromacs/bin:/opt/bio/gmap/bin:/opt/bio/tigr/bin:/opt/bio/autodocksuite/bin:/opt/bio/wgs/bin:/opt/eclipse:/opt/ganglia/bin:/opt/ganglia/sbin:/opt/rocks/bin:/opt/rocks/sbin:/opt/condor/bin:/opt/condor/sbin:/opt/gridengine/bin/lx26-amd64:/usr/bin:/usr/local/bin:/bin:/usr/java/latest/bin
    # Grid Engine path
    export PATH=$PATH:/opt/gridengine/bin/linux-x64
fi

# 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
python_version=$(python --version 2>&1 | cut -d " " -f2 | cut -d "." -f -2)
export PYTHONPATH=$HOME/local/lib/python${python_version}/site-packages
export PYTHONIOENCODING=utf-8
unset python_version


#----------#
# 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

# R
R_version=$(R --version | head -1 | cut -d " " -f 3)
export R_LIBS_HOME="$HOME/.R-libs"

if [[ ! -d "${R_LIBS_HOME}/${R_version}" ]]
then
    mkdir "${R_LIBS_HOME}/${R_version}"
fi

export R_LIBS="${R_LIBS_HOME}/${R_version}"

# 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 =~ 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 =~ medusa* || $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 || -f /tmp/${USER}_sty.lock ]]
then
    # Create a screen lock with level of screen
    if [[ -f /tmp/${USER}_sty.lock ]]
    then
        export LC_STY=$(($(cat /tmp/${USER}_sty.lock) + 1))
    else
        export LC_STY=1
    fi

    # ssh function to change the behaviour of ssh
    function ssh {
        /usr/bin/ssh $@ "echo $LC_STY > /tmp/${USER}_sty.lock" &&
        /usr/bin/ssh -t $@ "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 running 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)." ; }

    [[ -f /tmp/${USER}_sty.lock ]] && rm /tmp/${USER}_sty.lock
fi



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

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

# Server message
if [[ ! $HOSTNAME =~ compute.* && -z $STY && -z $LC_STY ]]
then
    nb=$nb=======
    echo -e "\n\n"
    cat .welcome.msg | sed "s/HOSTNAME/$(echo $name Server | sed "s/^[m,h]/\U&/")/" | sed "s/=\*/$nb/g"
    echo -e "\n"
fi

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

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