#!/usr/bin/env bash

function __makeTerminalTitle() {
    local title=''

    local CURRENT_DIR="${PWD/#$HOME/\~}"

    if [ -n "${SSH_CONNECTION}" ] || [ $UID -eq 0 ]; then
        title+="`hostname`:${CURRENT_DIR} [`whoami`@`hostname -f`]"
    else
        title+="${CURRENT_DIR} [`whoami`]"
    fi

    echo -en '\033]2;'${title}'\007'
}

function __getMachineId() {
    if [ -f /etc/machine-id ]; then
        echo $((0x$(cat /etc/machine-id | head -c 15)))
    elif [ -x "$(which hostid 2>&1)" ]; then
        echo $(( (${#HOSTNAME}+0x$(hostid))))
    else
        echo "00000000"
    fi
}

function __makePS1() {
    local EXIT="$?"

    if [ ! -n "${HOST_COLOR}" ]; then
        local H=$(__getMachineId)
        HOST_COLOR=$(tput setaf $((H%5 + 2))) # foreground
    fi

    PS1=''

    if [ ${USER} == root ]; then
        PS1+="\[${Red}\]" # root
    elif [ ${USER} != ${LOGNAME} ]; then
        PS1+="\[${Blue}\]" # normal user
    else
        PS1+="\[${Green}\]" # normal user
    fi
    PS1+="\u\[${Color_Off}\]"

    if [ -n "${SSH_CONNECTION}" ] || [ $UID -eq 0 ]; then
        PS1+="\[${Purple}\]@\[${Color_Off}\]"
        PS1+="\[${UWhite}${HOST_COLOR}\]\h\[${Color_Off}\]" # host displayed only if ssh connection
    fi

    PS1+="\[${Purple}\]:\w" # working directory

    # screen sessions
    local SCREEN_PATHS="/var/run/screens/S-`whoami` /var/run/screen/S-`whoami` /var/run/uscreens/S-`whoami`"

    for screen_path in ${SCREEN_PATHS}; do
        if [ -d ${screen_path} ]; then
            SCREEN_JOBS=`ls ${screen_path} | wc -w`
            if [ ${SCREEN_JOBS} != 0 ]; then
                local current_screen="$(echo ${STY} | cut -d '.' -f 1)"
                if [ -n "${current_screen}" ]; then
                    current_screen=":${current_screen}"
                fi
                PS1+=" \[${BGreen}\][s${SCREEN_JOBS}${current_screen}]\[${Color_Off}\]"
            fi
            break
        fi
    done

    # git branch
    if [ -x "`which git 2>&1`" ]; then
        local branch="$(git name-rev --name-only HEAD 2>/dev/null)"

        if [ -n "${branch}" ]; then
            local git_status="$(git status --porcelain -b 2>/dev/null)"
            local letters="$( echo "${git_status}" | grep --regexp=' \w ' | sed -e 's/^\s\?\(\w\)\s.*$/\1/' )"
            local untracked="$( echo "${git_status}" | grep -F '?? ' | sed -e 's/^\?\(\?\)\s.*$/\1/' )"
            local status_line="$( echo -e "${letters}\n${untracked}" | sort | uniq | tr -d '[:space:]' )"
            PS1+=" \[${Blue}\](git: ${branch}"
            if [ -n "${status_line}" ]; then
                PS1+=" ${status_line}"
            fi
            PS1+=")\[${Color_Off}\]"
        fi
    fi

    PS1+="\n"

    # exit code
    if [ ${EXIT} != 0 ]; then
        PS1+="\[${BRed}\][!${EXIT}]\[${Color_Off}\]"
    else
        PS1+="\[${Green}\][${EXIT}]\[${Color_Off}\]"
    fi

    PS1+="\[${Purple}\]->\[${Color_Off}\] " # prompt

    __makeTerminalTitle
}