#! /usr/bin/bash

#  This script is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License version 2 as
#  published by the Free Software Foundation.
#
#  See the COPYING and AUTHORS files for more details.

# Read in library functions
if [ "$(type -t patch_file_name)" != function ]
then
	if ! [ -r /usr/share/quilt/scripts/patchfns ]
	then
		echo "Cannot read library /usr/share/quilt/scripts/patchfns" >&2
		exit 1
	fi
	. /usr/share/quilt/scripts/patchfns
fi

usage()
{
	printf $"Usage: quilt fold [-p strip-level]\n"
	if [ x$1 = x-h ]
	then
		printf $"
Integrate the patch read from standard input into the topmost patch:
After making sure that all files modified are part of the topmost
patch, the patch is applied with the specified strip level (which
defaults to 1).

-p strip-level
	The number of pathname components to strip from file names
	when applying patchfile.
"

		exit 0
	else
		exit 1
	fi
}

options=`getopt -o p:qh -- "$@"`

if [ $? -ne 0 ]
then
	usage
fi

eval set -- "$options"

while true
do
	case "$1" in
	-p)
		opt_strip_level=$2
		shift 2 ;;
	-q)
		opt_silent=1
		shift ;;
	-h)
		usage -h ;;
	--)
		shift
		break ;;
	esac
done

if [ $# -ne 0 ]
then
	usage
fi

: ${opt_strip_level:=1}
[ -n "$opt_silent" ] && silent=-s

top=$(top_patch)
if [ -z "$top" ]
then
	printf $"No patches applied\n" >&2
	exit 1
fi

trap "failed=1" SIGINT

workdir=$(gen_tempfile -d $PWD)
/usr/bin/patch $QUILT_PATCH_OPTS -p$opt_strip_level $silent --backup --prefix="$workdir/" -E \
|| failed=1

if [ -z "$failed" ]
then
	# Copy additional files from workdir to the backup directory
	# For this patch
	for file in $(find $workdir -type f -a ! -path "$workdir/.timestamp")
	do
		file="${file:${#workdir}+1}"
		backup_file="$(backup_file_name $top "$file")"
		if ! [ -e "$backup_file" ]
		then
			if ! mkdir -p "$(dirname "$backup_file")" ||
			   ! ln "$workdir/$file" "$backup_file"
			then
				failed=1
				break
			fi
		fi
	done
fi
if [ -n "$failed" ]
then
	# Restore all files to the state from before applying the patch
	for file in $(find $workdir -type f -a ! -path "$workdir/.timestamp")
	do
		file="${file:${#workdir}+1}"
		if ! mv -f "$workdir/$file" "$file"
		then
			printf $"File %s may be corrupted\n" "$file" >&2
		fi
	done
	rm -rf $workdir
	exit 1
fi

rm -rf $workdir
exit 0
### Local Variables:
### mode: shell-script
### End:
# vim:filetype=sh
