#!/bin/sh
#
# Copyright (c) Josef "Jeff" Sipek, 2007-2011
#

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

_main() {

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

patch=`get_top`
if [ -z "$patch" ]; then
	die "No patches are applied."
fi

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

# Rename patches smartly
if [ $# -eq 1 ]; then
	newpatch="$1"
else
	base=$(echo "$patch" \
		| sed -r -e 's:(\.diff?|\.patch)$::')
	num=$(echo "$base" | sed -nre 's:.*-([0-9]+)$:\1:'p)
	[ -n "$num" ] || num=1
	newpatch="${base%-$num}-$(($num+1))${patch#$base}"
fi

if ! valid_patchname "$newpatch"; then
	die "The specified patch name contains invalid characters (:)."
fi

if [ -e "$GUILT_DIR/$branch/$newpatch" ]; then
	die "Patch \"$newpatch\" already exists. Choose another name."
fi

# copy the patch
cp "$GUILT_DIR/$branch/$patch" "$GUILT_DIR/$branch/$newpatch"

# replace the series & applied file references
series_rename_patch "$patch" "$newpatch"
applied_rename_patch "$patch" "$newpatch"
ref_rename_patch "$patch" "$newpatch"

}
