####################################################
# Customized configuration for ZSH based on prezto #
####################################################

#
# Exit if asked
#
if [[ "${DISABLE_DOTFILES_SYS}" = 1 ]]; then
    return
fi

#
# TMPDIR
#
export TMPDIR="${HOME}/tmp"
if [[ ! -d "${TMPDIR}" ]]; then
    mkdir -p "${TMPDIR}"
fi

#
# Using zpresto
#
export ZDOTDIR="$(dirname "$(readlink -f "${0}")")"
if [[ -f "${ZDOTDIR}/prezto/init.zsh" ]]; then
    source "${ZDOTDIR}/prezto/init.zsh"
    zstyle ':completion::complete:*' cache-path "${TMPDIR}/.zcompcache"
    # Remove first '\n' in PS1
    export PS1="$(echo "${PS1}" | sed ':a;N;$!ba;s/\n//')"
    # Add jobs count at the end of the first line
    export PS1="$(echo "${PS1}" | sed ':a;N;$!ba;s/\n/%1(j. with %F{161}%j%f job(s).)\n/')"
fi

#
# Load some colors
#

autoload colors zsh/terminfo
if [[ "${terminfo[colors]}" -ge 8 ]]; then
    colors
fi
for color in RED GREEN YELLOW BLUE MAGENTA CYAN ORANGE WHITE; do
    eval COLOR_$color='$terminfo[bold]$fg[${(L)color}]'
    eval COLOR_LIGHT_$color='$fg[${(L)color}]'
done
COLOR_RESET="$terminfo[sgr0]"

#
# Pager
#

VIMPAGER="$(readlink -f "${ZDOTDIR}/../tools/vimpager/vimpager")"
if (( $+commands[vim] )) && [[ -f "${VIMPAGER}" ]]; then
    export PAGER="${VIMPAGER}"
    alias less="${PAGER}"
    alias more="${PAGER}"
    export VIMPAGER_RC="$(readlink -f "${ZDOTDIR}/../tools/vim/vimpagerrc")"
    if [[ ! -f "${VIMPAGER_RC}" ]]; then
        unset VIMPAGER_RC
    fi
elif (( $+commands[less] )); then
    export PAGER=less
    alias more="${PAGER}"
elif (( $+commands[more] )); then
    export PAGER=more
fi
export GIT_PAGER="${PAGER}"
unset VIMPAGER

#
# Vim
#

VIMRC="$(readlink -f "${ZDOTDIR}/../tools/vim/vimrc")"
if [[ -f "${VIMRC}" ]]; then
    export VIMINIT="source ${VIMRC}"
fi
unset VIMRC

#
# Git
#

GIT_OPTIONS=()
if [[ -n "${LC_SSH_FULLNAME}" ]]; then
    GIT_OPTIONS+=(-c "user.name=${LC_SSH_FULLNAME}")
fi
if [[ -n "${LC_SSH_EMAIL}" ]]; then
    GIT_OPTIONS+=(-c "user.email=${LC_SSH_EMAIL}")
fi
export GIT_OPTIONS

export GIT_FAKE_HOME="$(readlink -f "${ZDOTDIR}/../tools/git")"
if [[ -f "${GIT_FAKE_HOME}/.gitconfig" ]]; then
    git() {
        (
            export LC_MESSAGES='en_US.UTF-8'
            export HOME="${GIT_FAKE_HOME}"
            =git ${GIT_OPTIONS} $@
        )
    }
    alias g='git'
fi

#
# Tmux
#
TMUX_OPTS="-2"
TMUX_CONF="$(readlink -f "${ZDOTDIR}/../tools/tmux/tmux.conf")"
if [[ -f "${TMUX_CONF}" ]]; then
    TMUX_OPTS="${TMUX_OPTS} -f ${TMUX_CONF}"
fi
alias tmux="TMPDIR= tmux ${TMUX_OPTS}"
unset TMUX_OPTS TMUX_CONF

#
# Common aliases / functions
#

alias ls='ls -h --color=auto'
alias l='ls -lh --color=auto'

alias rm='rm -i'
alias mv='mv -i'
alias cp='cp -i'

export GREP_OPTIONS="--color=auto"
alias mgrep="grep -rnisH"

alias rsu="sudo -E zsh"
alias reloadsh="exec zsh"

alias md="mkdir -p"
mcd() { mkdir -p "$@" && cd "$@" }

alias aug='sudo apt-get update && sudo apt-get upgrade'

if (( $+commands[ccze] )) ; then
    alias alog='tail -n 300 -F /var/log/auth.log | ccze'
    alias mlog='tail -n 300 -F /var/log/mail.log | ccze'
    alias slog='tail -n 300 -F /var/log/syslog | ccze'
else
    alias alog='tail -n 300 -F /var/log/auth.log'
    alias mlog='tail -n 300 -F /var/log/mail.log'
    alias slog='tail -n 300 -F /var/log/syslog'
fi

alias sscp_nosec='scp -o '\''StrictHostKeyChecking=no'\'' -o '\''UserKnownHostsFile=/dev/null'\'
alias ssh_nosec='ssh -o '\''StrictHostKeyChecking=no'\'' -o '\''UserKnownHostsFile=/dev/null'\'


#
# History options
#

setopt extendedhistory      # add a timestamp and the duration of each command
setopt sharehistory         # _all_ zsh sessions share the same history files
setopt histignorealldups    # ignores duplications
export HISTSIZE=1000000
export SAVEHIST=1000000
export HISTFILE="${TMPDIR}/.zhistory"


#
# Zsh options
#

export LISTPROMPT           # in order to scroll if completion list is too big

setopt clobber              # Allows > redirection to truncate existing files, and >> to create files
setopt checkjobs            # Report the status of background and suspended jobs before exiting a shell
setopt auto_cd              # a command like % /usr/local is equivalent to cd /usr/local
setopt nohup                # don't send HUP signal when closing term session
setopt extended_glob        # in order to use #, ~ and ^ for filename generation
setopt always_to_end        # move to cursor to the end after completion
setopt notify               # report the status of backgrounds jobs immediately
setopt correct              # try to correct the spelling if possible
setopt noflowcontrol        # disable xon/xoff
setopt histnostore          # don't store history command in history
setopt nobanghist           # don't care of '!' in commands
setopt emacs                # zle in emacs mode
setopt pushdignoredups      # ignore dups in pushd stack
setopt auto_continue        # send SIGCONT to jobs disowned
setopt auto_list            # list choice on ambiguous command
setopt auto_pushd           # cd = pushd
setopt pushd_ignore_dups    # ignore dups in pushd
setopt pushd_silent         # don't print stack after push/pop
setopt bang_hist            # yeah ! expansion (use bash !$ for example)
setopt chase_links          # cd to a symlink is in fact cd to the true dir
setopt ksh_option_print     # modify setopt output
setopt long_list_jobs       # list jobs in long format
setopt no_rm_star_wait      # dont't idle 10 seconds


#
# Zle config
#

# autoescape specials chars with urls
autoload -U url-quote-magic
zle -N self-insert url-quote-magic

# insert sudo at beggining of current command
insert-sudo-prefix () {
    local prefix
    prefix='sudo'
    if [ "${BUFFER:0:${#prefix}}" != "$prefix" ]; then
        BUFFER="$prefix $BUFFER"
        CURSOR=$(($CURSOR + $#prefix + 1))
    fi
}
zle -N insert-sudo-prefix
bindkey "^b" insert-sudo-prefix

# make home and end keys work with tmux
bindkey "^[[H" beginning-of-line
bindkey "^[[F" end-of-line


#
# MOTD
#

if [[ "${LC_SSH_VARS}" = 1 ]]; then
    if [[ -z "${TMUX}" ]] && [[ -z "${SUDO_UID}" ]]; then
        if [[ -z "${LC_SSH_EMAIL}" || -z "${LC_SSH_FULLNAME}" ]]; then
            printf "\n${COLOR_RED}You environment seems to not be properly configured: LC_SSH_EMAIL and LC_SSH_FULLNAME have to be set and forwarded through the ssh connection.${COLOR_RESET}\n"
        else
            printf "\n${COLOR_LIGHT_GREEN}You are logged in as ${COLOR_YELLOW}${LC_SSH_FULLNAME}${COLOR_RESET} <${COLOR_YELLOW}${LC_SSH_EMAIL}${COLOR_RESET}>\n"
        fi
        if [[ ! -e "${SSH_AUTH_SOCK}" ]]; then
            printf "${COLOR_LIGHT_YELLOW}Be warned that your ssh agent is not forwarded${COLOR_RESET}\n"
        fi
    fi
fi