#!/bin/zsh

################################################################################
# Utility functions for the prompt                                             #
################################################################################



local ZSH_THEME_VIRTUALENV_PREFIX=" %{$fg_bold[green]%}(%{%b$fg[green]%}"
local ZSH_THEME_VIRTUALENV_SUFFIX="%{$reset_color$fg_bold[green]%})%{$reset_color%}"

# Depending if root or not, displays the right prompt char
# and changes the color of the username
color_username () {
    if [[ $EUID -eq 0 ]]; then
        echo "%{$fg_bold[red]%}%n"
    else
        echo "%{$fg_bold[green]%}%n"
    fi
}

color_prompt_char () {
    if [[ $EUID -eq 0 ]]; then
        echo "%{$fg_no_bold[red]%}#%{$reset_color%}"
    else
        echo "%{$fg_no_bold[green]%}$%{$reset_color%}"
    fi
}

# Host coloring, specific to Rezometz
color_host () {
    local couleur_hote=""
    case $HOST in
        TwelveYearsAndStillGoingStrong|lharkinateur|BecauseROSThatSWhy|lharktop|blieuxor)
            couleur_hote=cyan;;
        chimay|orval)
            couleur_hote=magenta;;
        babel|taima|era|vidar|okami|athena)
            couleur_hote=red;;
        loki|skadi)
            couleur_hote=blue;;
        *)
            couleur_hote=white;;
    esac
    echo "%{$fg_bold[$couleur_hote]%}%m"
}


function virtualenv_prompt_info(){
    [[ -n ${VIRTUAL_ENV} ]] || return
    echo "${ZSH_THEME_VIRTUALENV_PREFIX:=[}${VIRTUAL_ENV:t}${ZSH_THEME_VIRTUALENV_SUFFIX:=]}"
}

last_status () {
    echo "%(?..%{$fg_no_bold[red]%}[%?])"
}

# disables prompt mangling in virtual_env/bin/activate
export VIRTUAL_ENV_DISABLE_PROMPT=1

function _prompt_chars() {
    if $(git rev-parse --is-inside-work-tree >/dev/null 2>&1); then
        local _GIT_CHAR="%{$fg_no_bold[blue]%}±%{$reset_color%}"
    else
        local _GIT_CHAR=''
    fi

    local _VENV_PROMPT="%{%}$(virtualenv_prompt_info)"

    echo "$_GIT_CHAR$_VENV_PROMPT$(last_status) $(color_prompt_char)"
}

function charge_batterie {
    local BATTERY=/sys/class/power_supply/BAT0
    local REM_CAP=`cat $BATTERY/charge_now`
    local FULL_CAP=`cat $BATTERY/charge_full`
    local BATSTATE=`cat $BATTERY/status`
    local CHARGE=$(( $REM_CAP * 100 / $FULL_CAP ))
    local Batterie=""
    case $BATSTATE in
        'Full')
            Batterie="~";;
        'Charging')
            Batterie="+";;
        'Discharging')
            Batterie="-";;
    esac
    # Maximum à 100%
    if [ $CHARGE -gt "99" ]
    then
        CHARGE=100
    fi
    local Couleur="magenta"
    if [ $CHARGE -gt "15" ]
    then
        Couleur="yellow"
    fi
    if [ $CHARGE -gt "30" ]
    then
        Couleur="green"
    fi

    echo %{$fg[${Couleur}]%B%}${Batterie}%{%b$fg[${Couleur_batt}]%}$CHARGE%%%{$reset_color%}
}

space_sh_git_branch () {
    local ref=$(command git symbolic-ref HEAD 2> /dev/null) || \
        ref=$(command git rev-parse --short HEAD 2> /dev/null) || return
    echo "${ref#refs/heads/}"
}

space_sh_git_status () {
    local ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg_no_bold[green]%}✓"
    local ZSH_THEME_GIT_PROMPT_AHEAD="%{$fg_no_bold[cyan]%}▴"
    local ZSH_THEME_GIT_PROMPT_BEHIND="%{$fg_no_bold[magenta]%}▾"
    local ZSH_THEME_GIT_PROMPT_STAGED="%{$fg_no_bold[green]%}●"
    local ZSH_THEME_GIT_PROMPT_UNSTAGED="%{$fg_no_bold[yellow]%}●"
    local ZSH_THEME_GIT_PROMPT_UNTRACKED="%{$fg_no_bold[red]%}●"

    _INDEX=$(command git status --porcelain -b 2> /dev/null)
    local _STATUS=""
    if $(echo "$_INDEX" | grep '^[AMRD]. ' &> /dev/null); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_STAGED"
    fi
    if $(echo "$_INDEX" | grep '^.[MTD] ' &> /dev/null); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_UNSTAGED"
    fi
    if $(echo "$_INDEX" | command grep -E '^\?\? ' &> /dev/null); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_UNTRACKED"
    fi
    if $(echo "$_INDEX" | grep '^UU ' &> /dev/null); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_UNMERGED"
    fi
    if $(command git rev-parse --verify refs/stash >/dev/null 2>&1); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_STASHED"
    fi
    if $(echo "$_INDEX" | grep '^## .*ahead' &> /dev/null); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_AHEAD"
    elif $(echo "$_INDEX" | grep '^## .*behind' &> /dev/null); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_BEHIND"
    fi
    if $(echo "$_INDEX" | grep '^## .*diverged' &> /dev/null); then
        _STATUS="$_STATUS$ZSH_THEME_GIT_PROMPT_DIVERGED"
    fi

    echo $_STATUS
}

space_sh_git_prompt () {
    local ZSH_THEME_GIT_PROMPT_PREFIX="%{$fg_bold[green]%}[%{$fg_bold[blue]%}"
    local ZSH_THEME_GIT_PROMPT_SUFFIX="%{$fg_bold[green]%}]"

    local _branch=$(space_sh_git_branch)
    local _result=""
    if [[ "${_branch}x" != "x" ]]; then
        local _status=$(space_sh_git_status)
        _result="$ZSH_THEME_GIT_PROMPT_PREFIX$_branch"
        if [[ "${_status}x" != "x" ]]; then
            _result="$_result $_status"
        fi
        _result="$_result$ZSH_THEME_GIT_PROMPT_SUFFIX"
    fi
    echo $_result
}

prompt_msg () {
    # TODO clean up /dev/shm when prompt_msg not in use
    # TODO Use unique filename in case multiple people use the same prompt
    line=$(tail -1 /dev/shm/prompt_msg) 2> /dev/null
    case $line in
        update_rc)
            msg="Update ready for rc. Run uprc to proceed";;
        git_unpushed)
            msg="You have unpushed business in $HOME/rc";;
        git_network_unreachable)
            msg="Can't reach rc git repo";;
        update_sys*)
            nb_pkg=$(echo $line | grep -o '[0-9]*' | head -n 1)
            msg="Update ready for the system. $nb_pkg new package$([ $nb_pkg -gt 1 ] && echo s)";;
        *)
            msg="";;
    esac

    # Remove last message from stack before it drives us mad
    sed -i '$ d' /dev/shm/prompt_msg 2> /dev/null
    echo $msg
}

################################################################################
# Prompt display                                                               #
################################################################################

prompt_create () {
    # Carriage return to give the prompt some air
    PROMPT="%{$reset_color%}"$'\n'

    # Username, red when logged as root
    PROMPT+='$(color_username)'

    # @ symbol
    PROMPT+="%{$fg_bold[blue]%}@"

    # Hostname, colors defined just above
    PROMPT+="$(color_host)"

    # White space to separate host from pwd
    PROMPT+=" %{$reset_color%}"

    # Current working directory, use ~ when needed
    PROMPT+="%{$fg[yellow]%}"'%~'

    # Display current message
    PROMPT+="%{$fg[red]%} "'$(prompt_msg)'

    # Change the background for the whole line and line feed
    PROMPT+="%{$fg_bold[green]%}%E"$'\n'

    # Prompt characters for virtualenv, git and zsh
    PROMPT+='$(_prompt_chars)'" %{$reset_color%}"

    # Right prompt with current repo informations
    RPROMPT='$(space_sh_git_prompt)'"%E%{$reset_color%}"

    #PROMPT="$Heure $Utilisateur@$Machine %{$fg_no_bold[yellow]%}%~
    #%{$reset_color%}%# "
    #RPROMPT="\$(charge_batterie) %(!,%B[%?]%b,[%?])"

    #RPROMPT="${vcs_info_msg_0_} \$(charge_batterie) %(!,%B[%?]%b,[%?])"

    #RPROMPT=" %(!,%B[%?]%b,[%?])"

    # %{  %} pas d'affichage, à utiliser pour ne pas fausser le calcul de RPROMPT
    # $fg[color], $fg_(no_)bold[color], $reset_color
    # black red green yellow blue magenta cyan white

    eval PROMPT='$PROMPT'
    eval RPROMPT='$RPROMPT'
}

################################################################################
# Update checking                                                              #
################################################################################

check_rc_update () {
    # Get rc dir path
    RC_PATH=$(dirname "$(readlink -f ${(%):-%x})")

    CUR_DIR=`pwd`
    cd $RC_PATH

    # In case the network is down, don't lock the terminal
    timeout 6 git fetch > /dev/null 2>&1
    #
    # Timeout returns 124 on timeout
    if [ "$?" -ge "124" ]; then
        echo 'git_network_unreachable' >> /dev/shm/prompt_msg
    fi

    # Check if the repo is clean
    git_st=$(command git status --porcelain -b 2> /dev/null)
    if $(echo "$git_st" | grep '^## .*ahead' &> /dev/null); then
        echo 'git_unpushed' >> /dev/shm/prompt_msg
    elif $(echo "$git_st" | grep '^## .*behind' &> /dev/null); then
        echo 'update_rc' >> /dev/shm/prompt_msg
    fi

    cd $CUR_DIR
}

check_sys_update () {
    case $(lsb_release -i | awk -F ':\t' '/Distributor ID/{print $2}') in
        Arch)
            nb_maj=$(checkupdates | wc -l);;
        Debian|Ubuntu)
            nb_maj=$(aptitude search '~U' | wc -l);;
        VoidLinux)
            nb_maj=$(xbps-install -Sun | wc -l);;
    esac
    if [ $nb_maj -gt 0 ]; then
        echo "update_sys $nb_maj" >> /dev/shm/prompt_msg
    fi
}

################################################################################
# Commands                                                                     #
################################################################################

# Do the update
uprc () {
    RC_PATH=$(dirname "$(readlink -f ${(%):-%x})")
    cd $RC_PATH
    git pull --rebase --stat origin master
    $RC_PATH/install.sh
    cd - &> /dev/null
    source $HOME/.zshrc
}

# Syntax coloration for man
man() {
  env \
    LESS_TERMCAP_mb="$(printf "%s" "$fg_bold[red]")" \
    LESS_TERMCAP_md="$(printf "%s" "$fg_bold[red]")" \
    LESS_TERMCAP_me="$(printf "%s" "$reset_color")" \
    LESS_TERMCAP_se="$(printf "%s" "$reset_color")" \
    LESS_TERMCAP_so="$(printf "%s" "$bg[black]$fg[yellow]")" \
    LESS_TERMCAP_ue="$(printf "%s" "$reset_color")" \
    LESS_TERMCAP_us="$(printf "%s" "$fg_bold[blue]")" \
    man "$@"
}