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

USAGE="[-k] [<patchname>]"
if [ -z "$GUILT_VERSION" ]; then
	echo "Invoking `basename "$0"` directly is no longer supported." >&2
	exit 1
fi

_main() {

keep=
if [ "${1:-}" = "-k" ]; then
	keep=t
	shift
fi

if [ $# -gt 1 ]; then
	usage
fi

need_work_tree

if [ $# -eq 0 ]; then
	n=`wc -l < "$applied"`
	n=$(( n + 1 ))

	if [ $n -gt `get_series | wc -l` ]; then
		die "No unapplied patch to fold."
	fi

	patch="`get_series | sed -n -e ${n}p`"
	echo Selected patch $patch
else
	patch="${1:-}"
fi

if [ -z "$patch" ]; then
	die "No patch name supplied."
fi

# make sure it is a file
if [ ! -f "$GUILT_DIR/$branch/$patch" ]; then
	die "Patch $patch does not exist."
fi

# make sure that there are no unapplied changes
if ! must_commit_first; then
	die "Uncommited changes detected. Refresh first."
fi

# make sure it is not applied
pline=`grep -x -e "$patch" < "$applied"`
if [ ! -z "$pline" ]; then
	die "Patch is applied. Pop the patch first."
fi

create_tmpdir
fold_patch "$patch"

# back it up just in case :)
[ -z "$keep" ] && mv "$GUILT_DIR/$branch/$patch" "$GUILT_DIR/$branch/$patch~"

}
