#!/bin/bash

source_if_exists "${ENVRCD_PATH}/profile/_assets/functions/exit_status"
source_if_exists "${ENVRCD_PATH}/profile/_assets/functions/truncate_pwd"
source_if_exists "${ENVRCD_PATH}/profile/_assets/functions/git_status"

function envrcd_prompt_rda {
    # show exit status of last command (needs to be the first function called). arguments: good, bad
    envrcd_function_exit_status
    #envrcd_function_exit_status "\[\e[32m\]<good>\[\e[0m\]" "\[\e[31m\]<bad>\[\e[0m\]"
    # truncate the directory path if it exceeds a certain length. arguments: spacefree pwdminlen
    envrcd_function_truncate_pwd

    if [ -z "${ENVRCD_COLOR_OFF}" ]; then
        local NO="\[\e[0m\]"  # NORMAL FONT
        local BO="\[\e[1m\]"  # BOLD FONT
        local LI="\[\e[2m\]"  # LIGHT FONT
        local BL="\[\e[30m\]" # BLACK
        local RE="\[\e[31m\]" # RED
        local GR="\[\e[32m\]" # GREEN
        local YE="\[\e[33m\]" # YELLOW
        local BL="\[\e[34m\]" # BLUE
        local MA="\[\e[35m\]" # MAGENTA
        local CY="\[\e[36m\]" # CYAN
        local WH="\[\e[37m\]" # WHITE

        if [ -z "${ENVRCD_INVENTORY}" ] || [ "${ENVRCD_INVENTORY}" = "production" ]; then
            # set root color to red (production)
            local RC=${RE}
        else
            # set root color to yellow (testing)
            local RC=${YE}
        fi
    fi

    # display git branch and dirty status. arguments: clean, dirty, delimiter, pre_clean, pre_dirty, post, master
    envrcd_function_git_status "${GR}+${GR}" "${YE}±${YE}" "" "${GR}[" "${YE}[" "]${NO}${YE}"

    # Check for python virtualenv
    local VENV="${VIRTUAL_ENV##*/}"
    VENV="${VENV:+(${VENV})}"

    # Check for chroot
    local CHROOT="${debian_chroot:+($debian_chroot)}"

    # Check for normal user account
    local USERAT="\u@"
    if [[ "${ENVRCD_USER}" == "rda" ]] && [[ "${HOSTNAME}" == "rda" || "${HOSTNAME}" == "compi" ]] && [[ "${USER}" == "maedersv" || "${USER}" == "rda" ]]; then
        USERAT=""
    fi

    local ENVRCD_PS1_ROOT="${EXITSTAT}${BO}${RC}\h${NO}:${BO}${BL}${TRUNCPWD}${NO}${YE}${GITSTAT}${VENV}${CHROOT}${NO}# "
    local ENVRCD_PS1_USER="${EXITSTAT}${BO}${GR}${USERAT}\h${NO}:${BO}${BL}${TRUNCPWD}${NO}${YE}${GITSTAT}${VENV}${CHROOT}${NO}$ "
    local ENVRCD_PS1_SUDO="${EXITSTAT}${BO}${RC}${USERAT}\h${NO}:${BO}${BL}${TRUNCPWD}${NO}${YE}${GITSTAT}${VENV}${CHROOT}${NO}$ "

    if [ -z "${ENVRCD_UID_NUM}" ]; then
        export PS1="${ENVRCD_PS1_ROOT}"
    else
        export PS1="${ENVRCD_PS1_USER}"
    fi

    export SUDO_PS1="${ENVRCD_PS1_SUDO}"
}

PROMPT_COMMAND=envrcd_prompt_rda