#!/bin/sh

# Git prompt module for Clifm
# Dependencies: git, sed, cut, tr, uniq, tail
# Author: L. Abramovich
# License: GPL2+

# Usage:
# Edit your prompt (via 'prompt edit') and add this code:
#
# RegularPrompt="... ${m_git_prompt_status} ..."

ESC=$(printf '\033')

cmd_output="$(git -c color.status=false status -sb 2>/dev/null)"

[ -z "$cmd_output" ] && exit 1

header="$(echo "$cmd_output" | sed -n 1p)"
files="$(echo "$cmd_output" | tail -n+2 | cut -c1-3 | uniq)"

case "$header" in
	*"/"*) tmp="$(echo "$header" | cut -d'/' -f2)" ;;
	*) tmp="$(echo "$header" | cut -d' ' -f2-10)" ;;
esac

branch="$(echo "$tmp" | cut -d' ' -f1)"

case "$tmp" in
	*"["*) ahead_behind="$(echo "$tmp" | cut -d' ' -f2-3 | tr -d '[]')" ;;
	*) ahead_behind="" ;;
esac

status=""

for i in $files; do
	case "$i" in
		".") status="${status}${ESC}[36m+" ;;
		"D"*) status="${status}${ESC}[31mD" ;;
		"M"*) status="${status}${ESC}[32mM" ;;
		"R"*) status="${status}${ESC}[35mR" ;;
		"U"*) status="${status}${ESC}[33mU" ;;
		"A"*) status="${status}${ESC}[32mA" ;;
		"??"*) status="${status}${ESC}[31m?" ;;
    esac
done

branch_color="${ESC}[22;35m"
sep_color="${ESC}[2;37m"
end_color="${ESC}[22;39m"

output="${branch_color}${branch}${sep_color}|"

if [ -n "$ahead_behind" ]; then
	ab_color="${ESC}[22;32m"
	[ "$(echo "$ahead_behind" | cut -b1)" != "a" ] && ab_color="${ESC}[22;31m"
	output="${output}${ab_color}${ahead_behind}${end_color}"
else
	output="${output}${ESC}[22;32m=${end_color}"
fi

[ -n "$status" ] && output="${output}${sep_color}|${end_color}${status}${end_color}"

printf '(%s)\n' "$output"

exit 0
