#!/bin/sh

#
# Add next patch in series
#

. patchfns 2>/dev/null ||
. /usr/lib/patch-scripts/patchfns 2>/dev/null ||
. $PATCHSCRIPTS_LIBDIR/patchfns 2>/dev/null ||
{
	echo "Impossible to find my library 'patchfns'."
	echo "Check your install, or go to the right directory"
	exit 1
}

usage()
{
	echo "Usage: pushpatch [-fmF] [npatches]"
	exit 1
}

opt_force=0
opt_merge=0
opt_fuzz=0

for i in $*
do
	case "$i" in
	-f)
		opt_force=1;;
	-F)
		opt_fuzz=1;;
	-m)
		opt_merge=1;;
	*)
		if [ -n "$NR" -o -n "$STOP_AT" ]
		then
			usage
		fi
		if is_numeric $i
		then
			NR=$i
		else
			NR=1000
			STOP_AT=$(stripit $i)
			if is_applied $STOP_AT
			then
				echo $STOP_AT is already applied
				exit 1
			fi
			if is_in_series $STOP_AT
			then
				true
			else
				echo $STOP_AT is not in the series file
				exit 1
			fi
		fi;;
	esac
done

[ $opt_force = 1 ] && force="-f"
[ $opt_merge = 1 ] && merge="-m"

if [ ! -e $P/series ]
then
	echo 'File "$P/series" not found'
	exit 1
fi

do_one()
{
	if [ $opt_fuzz = 1 ]
	then
		tmp=$(mktemp /tmp/XXXXXX)

		if ! $PATCHSCRIPTS_LIBDIR/apatch $* | tee $tmp
		then
			rm $tmp
			return 1
		elif grep '^Hunk #[0-9]' $tmp > /dev/null
		then
			rm $tmp
			return 1
		else
			rm $tmp
			return 0
		fi
	else
		if $PATCHSCRIPTS_LIBDIR/apatch $*
		then
			return 0
		else
			return 1
		fi
	fi
}

push_one()
{
	top=$($PATCHSCRIPTS_LIBDIR/toppatch)
	if [ x"$top" == x ]
	then
		todo=$(cat_series | head -1)
	else
		todo=$(next_patch)
	fi

	if [ x"$todo" = x ]
	then
		echo "series fully applied"
		exit 0
	fi

	if ! do_one $force $merge $todo
	then
		exit 1
	fi
	check_patch $todo
}

for i in $(seq 1 $NR)
do
	push_one
	if [ x$STOP_AT != "x" ]
	then
		if [ $STOP_AT == $($PATCHSCRIPTS_LIBDIR/toppatch) ]
		then
			exit 0
		fi
	fi
done
