# bashrc extra functions written for AOSC OSes, package "hg"
# by Arthur Wang

[ "$TERMCOLOR"=="8" ] && IRED="\e[0;31m" || IRED="\e[0;91m"

# Aliases from https://gist.github.com/shukydvir/1112265
alias hl='hg pull'
alias hp='hg push'
alias hd='hg diff'
alias hc='hg commit'
alias hco='hg checkout'
alias hb='hg branch'
alias hs='hg status'
alias ha='hg add .'

_detect_hg() {
	local _hg_dir="$1"
	local i=1
	if [ "${_hg_dir:0:1}" != "/" ] ; then
		echo "$FUNCNAME: absolute path required" >&2
		return 1
	fi
	# NOTE $_hg_dir is empty when it reaches /.
	while ! [ "/$_hg_dir" -ef "/" ] ; do
		if [ -d "$_hg_dir"/.hg ] ; then
			return 0
		fi
		_hg_dir="${_hg_dir%/*}"
	done
	[ -d /.hg ]
}

# From http://mediadoneright.com/content/ultimate-git-ps1-bash-prompt
# Modified for hg.
_ps1_hg_status() {
	# skip the check if possible, because hg is slow.
	_detect_hg $PWD || return 1
	hgb=$(hg branch 2>/dev/null) || return 1
	hgs=$(LC_ALL=C hg status 2>&1)
	if [ -z "$hgs" ]; then # unmodified
		echo -e "\01\e[1m\02@\01\e[0;32m\0002$hgb\01\e[0m\02"
	elif printf %s "$hgs" | grep -q '^[M!]'; then # modified or deleted
		echo -e "\01\e[1m\02@\01$IRED\0002$hgb\01\e[0m\02"
	elif printf %s "$hgs" | grep -q '^?'; then # untracked
		echo -e "\01\e[1m\02@\01\e[0;35m\0002$hgb\01\e[0m\02"
	else
		echo -e "\01\e[1m\02@\01\e[0;37m\0002$hgb\01\e[0m\02"
	fi
}

# A shorter one without color
# alias _hg_status='_st="$(hg branch)" && echo "@$st"'
