# Title: .bash_profile
# Author: Frédéric CHEVALIER <f15.chevalier@gmail.com>
# Version: 2.0
# Created in: 2014-01-07
# Modified in: 2016-06-10


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

# v2.0 - 2016-06-10: PATH updated / DISPLAY variable setup improved to allow remote display through ssh / start_agent with multikey management / start_agent calling improved / ssh aliases updated
# v1.3 - 2014-09-25: start_agent with limited ssh key lifetime added
# v1.2 - 2014-08-26: CHERE_INVOKING variable added 
# v1.1 - 2014-08-20: multiscreen remove because of .screenrc set up / Java variables added
# v1.0 - 2014-08-11: rewriting for better interplay with .bashrc
# v0.0 - 2014-01-07: creation



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

if [[ -f ~/.bashrc ]]
then
	source ~/.bashrc
fi



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

# Shortcuts for ssh operations
alias medusa='ssh medusa'
alias medusa2='ssh medusa2'
alias mendel='ssh mendel'
alias bulmer='ssh bulmer'

# Shortcut for vim
alias vi='vim'

# Path to Windows home
alias wh="cd /cygdrive/c/Users/$USER/"



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

#---------------#
# Personal Path #
#---------------#

# Java
export JAVA_HOME=/cygdrive/c/Users/$USER/AppData/Local/PortableApps/CommonFiles/Java
export PATH=$PATH:$JAVA_HOME/bin

# Chere variable (read by /etc/profile - important to start new shell session from current directory instead of $HOME)
export CHERE_INVOKING=1


#----------------#
# Window display #
#----------------#

# Set up the display variable to get an automatique display in the X server
if [[ -z "$SSH_CONNECTION" ]]
then
    export DISPLAY=:0.0
elif [[ -n "$SSH_CONNECTION" && -z "$DISPLAY" ]]
then
    flag="\$DISPLAY has no value"
elif [[ -n "$SSH_CONNECTION" && $DISPLAY =~ ":0.0" ]]
then
    flag="Value of \$DISPLAY is $DISPLAY"
fi

if [[ -n "$flag" ]]
then
    msg="${flag}. You cannot display remote windows. If -Y was used, set \"X11Forwarding yes\" in the server sshd_config file (see man sshd_config)."
    if [[ $(echo $PS1 | grep '\\e\[') ]]
    then
        echo -e "\n\e[33mWarning:\e[00m $msg\n"
    else
        echo "\nWarning: $msg\n"
    fi
fi


#-----------------------#
# SSH environment setup #
#-----------------------#

# Variables
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=259200 # seconds => 3 days

# 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 ssh-agent
        eval start_agent -t $lifetime ${SSH_KEYS[@]}
    fi
else
    eval start_agent -t $lifetime ${SSH_KEYS[@]}
fi
