#! /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()
{
	echo $"Usage: quilt fork [new_name]"
	if [ x$1 = x-h ]
	then
		echo $"
Fork the next patch. If new_name is missing, the name of the
forked patch will be the current patch name, followed by \"-2\".
If the patch name already ends in a dash-and-number, the number is
further incremented (e.g., patch.diff, patch-2.diff, patch-3.diff).
"
		exit 0
	else
		exit 1
	fi
}

options=`getopt -o h -- "$@"`

if [ $? -ne 0 ]
then
	usage
fi

eval set -- "$options"

while true
do
	case "$1" in
	-h)
		usage -h ;;
	--)
		shift
		break ;;
	esac
done

if [ $# -gt 1 ]
then
	usage
fi

next="$(patches_after $(top_patch) | head -n 1)"
if [ -z "$next" ]
then
	echo $"All patches applied" >&2
	exit 1
fi
next_file_name="$(patch_file_name $next)"

if [ $# -eq 1 ]
then
	patch_file="$1"
else
	set -- $(echo "$next" \
		 | sed -e 's: :\ :g' -e 's:-\([0-9]\+\)$: \1:')
	if [ $# -eq 1 ]; then
		patch_file="$1-2"
	else
		patch_file="$1-$[$2+1]"
	fi
	ext="$(echo $next_file_name \
	       | sed -e '\:\.\(diff\?\|patch\)\(\.gz\|\.bz2\|\)$:!d' \
		       -e 's:.*\(\.\(diff\?\|patch\)\(\.gz\|\.bz2\|\)\)$:\1:')"
	patch_file="$patch_file$ext"
fi

patch_file=$(echo $patch_file | sed -e 's/^'"$(quote_bre $QUILT_PATCHES)"'\///')
patch=$(stripit $patch_file)

if patch_in_series $patch || \
   [ -e "patches/$patch_file" ]
then
	echo $"Patch $patch exists already, please choose a new name"
	exit 1
fi

if ! rename_in_series "$next" "$patch_file" || \
   ! cp -p "$next_file_name" "$(patch_file_name $patch)"
then
	echo $"Fork of $next_file_name to $patch_file failed" >&2
	exit 1
fi

echo $"Fork of $next_file_name created as $(patch_file_name $patch)"

### Local Variables:
### mode: shell-script
### End:
# vim:filetype=sh
