# requires the following utilities:
#   git
#   GNU coreutils (for realpath)
#   BSD basename

prompt_command() {
    local retval=$?
    local branch="";
    local clean="";
    local cols=$COLUMNS

    local numcolor="\[\e[0;33m\]"
    local red="\[\e[0;31m\]"
    local sepcolor="\[\e[1;30m\]"
    local yellow="\[\e[0;33m\]"
    local brightyellow="\[\e[1;33m\]"
    local brightblue="\[\e[1;34m\]"
    local default="\[\e[0m\]"
    local green="\[\e[0;32m\]"

    if [[ $retval != 0 ]]; then
        numcolor="\[\e[1;41;33m\]"
    fi

    if git branch &>/dev/null; then
        branch="$green$(git branch 2>/dev/null | grep \* | cut -d ' ' -f 2-)"
        clean=$(git status | grep clean)
        if [ -z "$clean" ]; then clean="${red}✗"; else clean=""; fi
    fi

    userHost="${debian_chroot:+($debian_chroot)}$numcolor\!$red \u$sepcolor@${brightblue}\h${default}:${branch}${clean}"
    userHostExp="${debian_chroot:+($debian_chroot)}\! \u@\h:${branch}${clean}"
    userHostExp=${userHostExp@P}

    wrkDir="$default\w$green"
    wrkDirExp="\w"
    wrkDirExp=${wrkDirExp@P}

    userPrompt="\$${default}"

    if (( ${#userHostExp} + ${#wrkDirExp} < $cols - 20 )); then
      # We can fit everything on one line
      # echo "Oneline: $((${#userHostExp} + ${#wrkDirExp})) < $(($cols - 20))"
      PS1="${userHost} ${wrkDir}${userPrompt} "
    elif (( ${#userHostExp} + ${#wrkDirExp} < $cols + 6 )); then
      # We just need to put the prompt on it's own line
      # echo "Twoline: $((${#userHostExp} + ${#wrkDirExp})) < $(($cols + 6))"
      PS1="\n${userHost} ${wrkDir}\n${userPrompt} "
    else
      # We need to put the userHost on it's own line
      PS1="\n${userHost}\n"

      if (( ${#wrkDirExp} < $cols - 20 )); then
        # We can fit the prompt and working dir on one line
        # echo "Twoline2: $(( ${#wrkDirExp} )) < $(($cols - 20 ))"
        PS1+="${wrkDir}${userPrompt} "
      else
        # We have to put the prompt on it's own line
        # echo "Threeline"
        PS1+="${wrkDir}\n${userPrompt} "
      fi
    fi

    unset clean numcolor branch retval cols
    unset userHost userHostExp wrkDir wrkDirExp userPrompt userPromptExp
}

PROMPT_COMMAND=prompt_command

eval "$(thefuck --alias fixit)"
set -o vi

source ~/.bash_aliases
