#!/bin/bash

git_history () {
	if [ "$DISPLAY" ] ; then
		gitk "$@"
	else
		tig "$@"
	fi
}

git_record () {
	if [ "$DISPLAY" ] ; then
		git gui
	else
		git crecord
	fi
}

if [ "x$(git config --bool review.disable)" = xtrue ] ; then
	exit 0
fi
if git ls-files --others --exclude-standard --directory --no-empty-directory --error-unmatch -- ':/*' >/dev/null 2>/dev/null ; then
	git_record
fi
if ! git diff --no-ext-diff --quiet --exit-code ; then
	git_history --all ; exit
fi
if ! git diff-index --cached --quiet HEAD -- ; then
	git_history --all ; exit
fi
if git rev-parse --verify --quiet refs/stash > /dev/null ; then
	git_history --all ; exit
fi

history_args=()

for branch in $(git branch | tr -d '*') ; do
	case "$branch" in
		github)
			continue
		;;
		githubgithub)
			continue
		;;
		rejected/*)
			continue
		;;
	esac
	if review="$(git config --bool "branch.$branch.review")" && [ "x$review" = xfalse ] ; then
		continue
	fi
	if remote="$(git config "branch.$branch.remote")" ; then
		if [ "$remote" != . ] ; then
			remote="$remote/"
		else
			remote=""
		fi
		if git config "branch.$branch.merge" > /dev/null ; then
			count="$(git rev-list --count --left-right "$branch@{upstream}...$branch")"
			if [ "$count" != "0	0" ] ; then
				history_args+=("$branch@{upstream}...$branch")
			fi
		fi
	elif [ -n "$(git remote)" ] ; then
		history_args+=("$branch")
	fi
done

git_history "${history_args[@]}"
