<< //
Purpose: Bashrc for devcontainer at Fastnet SA
Version: 1.0
Create Date: 10 24th 2022
Author: Vincent Lauria <vincent@lauria.ch>
//

# History
if [[ ! -z "${HISTFILE_DIRECTORY}" && -d "${HISTFILE_DIRECTORY}" ]]; then
	export HISTCONTROL=ignoredups HISTFILE="${HISTFILE_DIRECTORY}/.bash_history"
fi

# Set the default git editor if not already set
if [[ -z "$(git config --get core.editor)" ]] && [[ -z "${GIT_EDITOR}" ]]; then
	if [[ "${TERM_PROGRAM}" = "vscode" ]]; then
		if [[ -n $(command -v code-insiders) && -z $(command -v code) ]]; then
			export GIT_EDITOR="code-insiders --wait"
		else 
			export GIT_EDITOR="code --wait"
		fi
	fi
fi

# Auto-completion
if [[ -f /etc/bash_completion ]]; then
	. /etc/bash_completion
fi

# Aliases
alias ls="ls --color=auto --group-directories-first"

# Colors
declare -A C

C[Red]="\[\e[0;31m\]"
C[RedBold]="\[\e[1;31m\]"
C[Green]="\[\e[0;32m\]"
C[GreenBold]="\[\e[1;32m\]"
C[Yellow]="\[\e[0;33m\]"
C[YellowBold]="\[\e[1;33m\]"
C[Blue]="\[\e[0;34m\]"
C[BlueBold]="\[\e[1;34m\]"
C[Purple]="\[\e[0;35m\]"
C[PurpleBold]="\[\e[1;35m\]"
C[LightBlue]="\[\e[0;36m\]"
C[LightBlueBold]="\[\e[1;36m\]"
C[End]="\[\e[0m\]"

prompt_userpart() {
	if [[ ! -z "${GITHUB_USER}" ]]; then
		echo -n "${C[Green]}@${GITHUB_USER} "
	else
		echo -n "${C[Green]}\u "
	fi

	export XIT=$?
	if [[ "$XIT" -ne "0" ]]; then
		echo -n "${C[RedBold]}➜${C[End]}"
	else
		echo -n "➜${C[End]}"
	fi
}

prompt_git_branch() {
	if [[ ! $(git rev-parse --is-inside-work-tree 2>/dev/null) = true ]]; then
		return
	fi

	if [[ ! "$(git config --get codespaces-theme.hide-status 2>/dev/null)" != 1 ]]; then
		return
	fi

	local BRANCH=$(git symbolic-ref --short HEAD 2>/dev/null || git rev-parse --short HEAD 2>/dev/null);

	if [[ "${BRANCH}" != "" ]]; then
		if (( "${#BRANCH}" > 15 )); then
			BRANCH="…${BRANCH:${#BRANCH}-15:15}"
		fi

		echo -n " ${C[LightBlue]}[${C[Purple]}${BRANCH}"
		if git ls-files --error-unmatch -m --directory \
				--no-empty-directory -o --exclude-standard ":/*" > /dev/null 2>&1; then
			echo -n " ${C[RedBold]}✗"
		else
			echo -n " ${C[GreenBold]}✔︎"
		fi
		echo -n "${C[LightBlue]}]${C[End]}"
	fi
}

prompt_command() {
	if [[ ! -z "${HISTFILE_DIRECTORY}" && -d "${HISTFILE_DIRECTORY}" ]]; then
		history -a
	fi
	PS1="$(prompt_userpart) ${C[LightBlue]}\w${C[End]}$(prompt_git_branch) \$ "
}

PROMPT_COMMAND=prompt_command
