#
# Prompt config
#

setopt prompt_subst

# enable colors
autoload colors zsh/terminfo
if [[ "$terminfo[colors]" -ge 8 ]]; then
    colors
fi
for color in RED GREEN YELLOW BLUE MAGENTA CYAN WHITE; do
    eval PR_$color='%{$terminfo[bold]$fg[${(L)color}]%}'
    eval PR_LIGHT_$color='%{$fg[${(L)color}]%}'
done
PR_NO_COLOUR="%{$terminfo[sgr0]%}"

export PR_OS_NAME=$(uname -s)
export PR_OS_ARCH=$(uname -m)

if [ -f /etc/debian_version ]; then

    # ugly way to detect Ubuntu chroots
    LSB_NAME=$(egrep 'DISTRIB_(ID|CODENAME)' /etc/lsb-release 2>/dev/null \
                | tr '\n' '=' | cut -d'=' -f2,4 | tr '=' ' ')

    if [ "$PR_OS_NAME" = "Linux" ]; then
        PR_OS_NAME="Debian $(</etc/debian_version)"
    else
        PR_OS_NAME="Debian/${PR_OS_NAME} $(</etc/debian_version)"
    fi
    if [ -f /etc/debian_chroot ]; then
        if [ -n "$LSB_NAME" ]; then
            PR_OS_NAME="${PR_OS_NAME} ${PR_LIGHT_RED}chroot:${PR_WHITE}$LSB_NAME"
        else
            PR_OS_NAME="${PR_OS_NAME} ${PR_LIGHT_RED}chroot:${PR_WHITE}Debian $(</etc/debian_version)"
        fi
    else
        if [ -n "$LSB_NAME" ]; then
            PR_OS_NAME="$LSB_NAME"
        fi
    fi

    unset LSB_NAME
fi
PR_OS_NAME="${PR_OS_NAME} ${PR_OS_ARCH}"

if [ "$TERM" = "screen" -a -n "$WINDOW" ]; then
    export PR_OS_PTY="scr/$WINDOW"
else
    export PR_OS_PTY=$(print -P %l)
fi

if [ -n "$SSH_CLIENT" ]; then
    export PR_OS_SSH="${PR_LIGHT_RED}ssh:"
else
    export PR_OS_SSH=
fi

if [ "$UID" = 0 ]; then
    export PR_ROOT_PREFIX='*'
else
    export PR_ROOT_PREFIX=
fi

function mytitle {
    # if running screen, setting current directory name in caption/statusbar
    [ "$TERM" = "screen" ] && echo -ne "\033k${PR_ROOT_PREFIX}${1}\033\\"
    # if running 'xterm like' terminal setting directory name in title bar
    [ "$TERM" = "xterm" ] && echo -ne "\033]0;${PR_ROOT_PREFIX}${1}\007"
}

function preexec {
    local -a buffer
    buffer=(${=1})
    mytitle "$buffer[1]"
}

function precmd {
    mytitle "$(print -P %~)"
}

myprompt() {    
    if [ "$TERM" = "dumb" ]; then
    PROMPT="-(%n@%m)-(%(!.%d.%~))->"
    else
    PROMPT='\
${PR_BLUE}\
%1(j.-(${PR_YELLOW}jobs:${PR_WHITE}%j${PR_BLUE}).)\
${PR_BLUE}-(\
%(!.${PR_RED}%n.${PR_LIGHT_GREEN}%n)\
${PR_WHITE}@${PR_OS_SSH}${PR_MAGENTA}%m${PR_WHITE} ${PR_OS_PTY}${PR_BLUE})-(\
${PR_WHITE}${PR_OS_NAME}${PR_BLUE})-(${PR_WHITE}%(!.%d.%~)${PR_BLUE})
%0(?..${PR_RED}ret:${PR_WHITE}%?${PR_BLUE})>${PR_NO_COLOUR}'
    fi
}

myprompt

