# Title: .bashrc
# Author: Frédéric CHEVALIER <f15.chevalier@gmail.com>
# Version: 1.7
# Created in: 2012-05-26
# Modified in: 2014-09-25



#==========#
# Comments #
#==========#

# ~/.bashrc: executed by bash(1) for non-login shells
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc) for examples



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

# v1.7 - 2014-09-25: start_agent function improved
# v1.6 - 2014-08-16: new history entries to ignore / screen and :q aliases
# v1.5 - 2014-08-06: autocd set on / R alias added /bk function turned in a separate script / SSH environment setup moved in bash_profile
# v1.4 - 2014-07-26: ssh_agent function for SSH key management added / ssh_agent called when used SSH connexion / wf alias updated
# v1.3 - 2014-07-19: bug correction for PS1 (\[\e and \] missing for each color) / typo corrections
# v1.2 - 2014-07-06: h and t aliases corrected / m alias added / quit function added / R env variables added
# v1.1 - 2014-07-02: bug corrections in trash function and EDITOR set up / exit and diff aliases added
# v1.0 - 2014-06-22: file reorganization / aliases added
# v0.0 - 2012-05-26: creation



#=======================#
# User specific options #
#=======================#

# If not running interactively, don't do anything
[[ -z "$PS1" ]] && return

# Enable programmable completion features
if [[ -f /etc/bash_completion ]] && ! shopt -oq posix
then
    . /etc/bash_completion
fi

# Set variable identifying the chroot you work in (used in the prompt below)
if [[ -z "$debian_chroot" && -r /etc/debian_chroot ]]
then
    debian_chroot=$(cat /etc/debian_chroot)
fi


#-----------------#
# History options #
#-----------------#

# Ignore duplicates and spaces
export HISTCONTROL=ignoreboth

# Ignore some controlling instructions
# The '&' is a special pattern which suppresses duplicate entries.
export HISTIGNORE=$'[ \t]*:&:[fb]g:exit:*q:screen*'
# export HISTIGNORE=$'[ \t]*:&:[fb]g:exit:ls' # Ignore the ls command as well

# Whenever displaying the prompt, write the previous line to disk
#export PROMPT_COMMAND="history -a"

# Maximum command retain in the .bash_history file
export HISTSIZE=2000

# Add timestamps for each command
export HISTTIMEFORMAT="$(echo -e '\e[0;32m')[ %d/%m/%Y %H:%M:%S ] $(echo -e '\e[0m') "

# Append to the history file, don't overwrite it
shopt -s histappend

# Allow edition of history command
shopt -s histverify


#---------------#
# Shell options #
#---------------#

# Adjust each LINES and COLUMNS after each command
shopt -s checkwinsize

# Manage typing error
shopt -s cdspell

# Avoid cd usage
shopt -s autocd

# Make less more friendly for non-text input files, see lesspipe(1)
[[ -x /usr/bin/lesspipe ]] && eval "$(SHELL=/bin/sh lesspipe)"


#---------------#
# Color options #
#---------------#

# Set a fancy prompt (non-color, unless we know we "want" color)
force_color_prompt=yes

if [ -n "$force_color_prompt" ]
then
    if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null
    then
		# We have color support; assume it's compliant with Ecma-48
		# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
		# a case would tend to support setf rather than setaf.)
		color_prompt=yes
    else
		color_prompt=
    fi
fi

if [[ "$color_prompt" == "yes" ]]
then
	if [[ -n "$SSH_CONNECTION" ]]
    then
		PS1='\[\e[31m\][$(date +%H:%M) \u@\[\e[01;35m\]\h\[\e[00;31m\]:\[\e[33m\]\W\[\e[31m\]]\[\e[00m\]\$ '
	else
		PS1='\[\e[36m\][$(date +%H:%M) \u@\[\e[01;35m\]\h\[\e[00;36m\]:\[\e[33m\]\W\[\e[36m\]]\[\e[00m\]\$ '
	fi
else
    PS1='[$(date +%H:%M) \u@\h:\W]\$ '
fi


# Add chroot if present
PS1="${debian_chroot:+($debian_chroot)}$PS1"


# Enable colors for man pages (adapt colors as needed)
if [[ "$color_prompt" == "yes" ]]
then
	export LESS_TERMCAP_mb=$'\e[01;31m'    # blink start
	export LESS_TERMCAP_md=$'\e[01;33m'    # bold start (if white bg: $'\e[01;31m')
	export LESS_TERMCAP_me=$'\e[0m'        # end
	export LESS_TERMCAP_se=$'\e[0m'        # end
	export LESS_TERMCAP_so=$'\e[01;44;33m' # status line start
	export LESS_TERMCAP_ue=$'\e[0m'        # end
	export LESS_TERMCAP_us=$'\e[01;35m'    # underlined start (if white bg: $'\e[01;32m')
fi

unset color_prompt force_color_prompt


# Enable color support of ls and grep and also add handy aliases
if [[ -x /usr/bin/dircolors ]]
then
    test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"

    alias ls="ls --color=auto --group-directories-first -h -C"
    alias dir="dir --color=auto"
    alias vdir="vdir --color=auto"

    alias grep="grep --color=auto"
    alias fgrep="fgrep --color=auto"
    alias egrep="egrep --color=auto"

    alias tree="tree -C"
fi



#=======================#
# User specific aliases #
#=======================#

# Moving in directories
alias ..="cd .."
alias ....="cd ../.."

# Listing files
alias l="ls"
alias ll="l -l"
alias lr="l --recursive"
alias llr="ll --recursive"
alias la="ls -A"
alias lla="la -l"

# File manipulations
alias diff="diff -y --suppress-common-lines"

# Internet
alias dl="wget -c"
alias scp="scp -pr"
alias ssh="ssh -Y"
alias wf="ssh -i $HOME/.ssh/id_main-server.dsa wf@vaderf.com"
alias fwf="ssh fred@vaderf.com"
alias heron="ssh fcheval@heron.txbiomedgenetics.org"

# Disk space
alias df="df -h"
alias du="du -h"

# Safety aliases
#alias rm="rm --interactive"

# Misc short aliases
alias c="cat"
alias g="grep"
alias h="head"
alias t="tail"
alias m="more"
alias bye="exit"
alias :q="exit"
alias R="R --no-save"
alias s="screen -D -RR"
alias ns="screen"


# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [[ -f ~/.bash_aliases ]]
then
    . ~/.bash_aliases
fi


#=========================#
# User specific functions #
#=========================#

# cd improvment function
# This function defines a 'cd' replacement function capable of keeping,
# displaying and accessing history of visited directories, up to 10 entries.
# To use it, try 'cd --'.
# acd_func 1.0.5, 10-nov-2004
# Petar Marinov, http:/geocities.com/h2428, this is public domain
function cd_func {
    local x2 the_new_dir adir index
    local -i cnt

    if [[ $1 ==  "--" ]]
    then
        dirs -v
        return 0
    fi

    the_new_dir=$1
    [[ -z $1 ]] && the_new_dir=$HOME

    if [[ ${the_new_dir:0:1} == '-' ]]
    then
        # Extract dir N from dirs
        index=${the_new_dir:1}
        [[ -z $index ]] && index=1
        adir=$(dirs +$index)
        [[ -z $adir ]] && return 1
        the_new_dir=$adir
    fi

    # '~' has to be substituted by ${HOME}
    [[ ${the_new_dir:0:1} == '~' ]] && the_new_dir="${HOME}${the_new_dir:1}"

    # Now change to the new dir and add to the top of the stack
    pushd "${the_new_dir}" > /dev/null
    [[ $? -ne 0 ]] && return 1
    the_new_dir=$(pwd)

    # Trim down everything beyond 11th entry
    popd -n +11 2>/dev/null 1>/dev/null

    # Remove any other occurence of this dir, skipping the top of the stack
    for ((cnt=1; cnt <= 10; cnt++))
    do
        x2=$(dirs +${cnt} 2>/dev/null)
        [[ $? -ne 0 ]] && return 0
        [[ ${x2:0:1} == '~' ]] && x2="${HOME}${x2:1}"
        if [[ "${x2}" == "${the_new_dir}" ]]
        then
            popd -n +$cnt 2>/dev/null 1>/dev/null
            cnt=cnt-1
        fi
    done

    return 0
}

alias cd=cd_func


# Extract function
function extract {
	if [[ -f $1 ]]
	then
		case $1 in
			*.tar.bz2 | *.tbz2	) tar xvjf $1 ;;
			*.tar.gz | *.tgz	) tar xvzf $1 ;;
			*.tar				) tar xvf $1 ;;
			*.gz				) gunzip $1 ;;
			*.bz2				) bunzip2 $1 ;;
			*.rar				) rar x $1 ;;
			*.zip | *.7z		) unzip $1 ;;
			*.Z					) uncompress $1 ;;
			*					) echo "don't know how to extract '$1'..." ;;
		esac
	else
		echo "'$1' is not a valid file!"
	fi
}


# Trash function
# Check if trash-cli is installed otherwize check for already existing .trash
if [[ $(which trash-put &> /dev/null ; echo $?) == 0 ]]
then
	alias trash='trash-put'
else
	if [[ -d $HOME/.trash/ ]]
	then
		alias trash='mv $1 -t $HOME/.trash/'
	else
		echo -e "\n\tNo trash set up: trash-cli not installed or $HOME/.trash/ does not exist.\n"
	fi
fi


# Quit function
function q {
    read -a ans -p "Do you want to exit [Y/n]? "

    if [[ -z $ans ]] ; then ans=Y ; fi

    case $ans in
        Y|y|yes ) exit ;;
        N|n|no  ) ;;
        *       ) echo "Wrong choice" ;;
    esac
}


# SSH agent function
# Usage: function used to store SSH environment (SSH key in ssh-agent)
# See .bash_profile from servers for use
function start_agent {
    if [[ $LANG =~ ^fr ]]
    then
        msg1="Initialisation du nouvel agent SSH..."
        msg2="Opération réussi"
    else
        msg1="Initializing new SSH agent..."
        msg2="Succeeded"
    fi

    # SSH agent environment
    echo -e "\n${msg1}"
    ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
    echo -e "${msg2}\n"
    chmod 600 "${SSH_ENV}"
    source "${SSH_ENV}" > /dev/null

    # SSH key add ($@: useful to add ssh-add options like lifetime directly through start_agent)
    ssh-add $@ 
}



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

# Editor
if [[ $(which vim &> /dev/null ; echo $?) == 0 ]]
then
	export EDITOR="vim"
else
	export EDITOR="nano"
fi


# Personalized PATH
export PATH="$HOME/.local/bin:$PATH"


# LaTeX environment
export TEXMFHOME="$HOME/.texmf"


# R environment
export R_HISTFILE="$HOME/.Rhistory"
export R_HISTSIZE=$HISTSIZE


# SSH environment
export SSH_ENV="$HOME/.ssh/ssh_agent_$HOSTNAME"

