#!/bin/bash
#
# Copyright (c) Josef "Jeff" Sipek, 2006, 2007
#

USAGE="[ -f ] [-a | --all | <patchname>]"
. guilt

abort_flag="abort"


if [ "$1" == "-f" ]; then
	abort_flag=""
	shift
fi

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

patch="$1"

if [ "$patch" = "--all" -o "$patch" = "-a" ]; then
	# we are supposed to push all patches, get the last one out of
	# series

	eidx=`get_series | wc -l`
	if [ $eidx -eq 0 ]; then
		die "There are no patches to push"
	fi
elif [ -z "$patch" ]; then
	# we are supposed to push only the next patch onto the stack

	eidx=`wc -l < $applied`
	eidx=`expr $eidx + 1`
else
	# we're supposed to push only up to a patch, make sure the patch is
	# in the series

	eidx=`get_series | grep -ne "^$patch\$" | cut -d: -f1`
	if [ -z "$eidx" ]; then
		die "Patch $patch is not in the series"
	fi
fi

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

# now, find the starting patch
sidx=`wc -l < $applied`
sidx=`expr $sidx + 1`

idx=0
for p in `get_series`; do
	idx=`expr $idx + 1`
	[ $idx -lt $sidx ] && continue
	[ $idx -gt $eidx ] && break

	echo "Applying patch..$p"
	if [ ! -f "$GUILT_DIR/$branch/$p" ]; then
		die "Patch $patch does not exist. Aborting."
	fi

	push_patch $p $abort_flag

	# bail if necessary
	if [ $? -eq 0 ]; then
		echo "Patch applied."
	elif [ -z "$abort_flag" ]; then
		die "Patch applied with rejects. Fix it up, and refresh."
	else
		die "To force apply this patch, use 'guilt push -f'"
	fi
done

