#!/usr/bin/sh
#
# Copyright (c) Josef "Jeff" Sipek, 2006-2013
#

USAGE="[-v | -g | -e | -n | -m]"
if [ -z "$GUILT_VERSION" ]; then
	echo "Invoking `basename "$0"` directly is no longer supported." >&2
	exit 1
fi

_main() {

numeric=''
edit=
verbose=
gui=
missing=
while case "$#" in 0) break ;; esac
do
	case "$1" in
	-v)
		verbose=t ;;
	-g)
		gui=t ;;
	-e)
		edit=t ;;
	-n)
		numeric='-n' ;;
	-m)
		missing=t ;;
	*)
		usage ;;
	esac
	shift
done

if [ ! -z "$edit" ]; then 
	git_editor "$series"
elif [ ! -z "$gui" ]; then
	[ -z "`get_top`" ] && die "No patches applied."
	bottom=`git rev-parse refs/patches/$branch/$(head_n 1 "$applied")`
	top=`git rev-parse refs/patches/$branch/$(tail -n 1 "$applied")`
	range="$bottom..$top"

	# FIXME, this doesn't quite work - it's perfectly fine with
	# "git rev-list", but gitk for whatever reason likes to include the
	# parent
	[ "$bottom" = "$top" ] && range="$bottom^..$bottom"

	gitk $range
elif [ ! -z "$missing" ]; then
	create_tmpdir
	ls -A "$GUILT_DIR/$branch" | grep -v -e '~$' -e '^guards$' -e '^series$' \
		-e '^status$' | sed 's,^,  ,' > "$tmpdir/curr"
	get_full_series | sort | sed 's,^,  ,' > "$tmpdir/exp"
	echo "Patches present in dir but missing from series:"
	comm -23 "$tmpdir/curr" "$tmpdir/exp"
	echo "Patches present in series but missing from dir:"
	comm -13 "$tmpdir/curr" "$tmpdir/exp"
elif [ -z "$verbose" ]; then
	if [ -n "$numeric" ]; then
		get_full_series | cat -n
	else
		get_full_series
	fi
else
	prefix="+"
	top=`get_top`

	get_full_series |
	while read patch; do
		if [ -z "$top" ]; then
			disp "  $patch"
		else
			if [ "$patch" = "$top" ]; then
				disp "= $patch"
				prefix=" "
                        elif [ $(check_guards "$patch"; echo $?) -eq 1 ]; then
				echo "  $patch"
			else
				disp "$prefix $patch"
			fi
		fi
	done | cat $numeric
fi

}
