#!/usr/bin/env bash

COLOR_RESET='\[\e[0m\]'
PROMPT_SUCCESS_COLOR='\[\e[0;34m\]'
PROMPT_FAILURE_COLOR='\[\e[0;31m\]'
DIR_COLOR='\[\e[0;33m\]'

# prompt rendering functions
preprocess_pwd() {
	name="$PWD"
	# if we're in the home directory, replace it with tilde
	[[ "$name" =~ ^"$NICE_HOME"(/|$) ]] && name="~${name#$NICE_HOME}"

	# replace all non-basename parts of the PWD with only the first two letters
	curdir=$(echo "$PWD" | sed -r 's|.*/(.+)$|\1|g')
	name=$(echo "$name" | sed -r 's|/(..)[^/]*|/\1|g' | sed -r 's|(.*/)(.+)$|\1|g')

	# if we're just in the home directory, don't show any path stuff
	[[ "$name" == "~" ]] && curdir=""

	# return our transformed PWD
	echo "$name$curdir"
}
export -f "preprocess_pwd"

prompt_command_func()
{
	RET=$?
	# set the color of the user and host based on the result of the previous
	# command
	if [ $RET -eq 0 ]; then
		STATUS_COLOR=$PROMPT_SUCCESS_COLOR
	else
		STATUS_COLOR=$PROMPT_FAILURE_COLOR
	fi;
	PS1="$STATUS_COLOR\u@\h$COLOR_RESET $DIR_COLOR$(eval "preprocess_pwd")$COLOR_RESET "
}
export -f "prompt_command_func"
export PROMPT_COMMAND="prompt_command_func"