#!/bin/sh

usage()
{
    echo "Apply the given patch and regenerate it if it has fuzzy hunks"
    echo
    echo "Usage: ${0##*/} [--help] dest_dir file patch_tool_options"
    echo
    echo "Options:"
    echo
    echo "	--help	 - print this help"
    echo "	dest_dir - root directory where the patches are applied with -p0"
    echo "	file	 - patch file to apply and update"
    echo "	patch_tool_options"
    echo "		 - options of the patch tool, see man patch"
    echo
    echo "Note: it does not refresh the given patch if the --dry-run or -R option is used"
}
					
if test "$1" = "--help" -o $# -lt 3 ; then
    usage
    exit 0;
fi

dest_dir="$1"
patch_file="$2"
shift
shift

if ! test -d "$dest_dir" ; then
    echo "Error: Directory does not exist: $dest_dir"
    exit 1;
fi

if ! test -f "$patch_file" ; then
    echo "Error: File does not exist: $patch_file"
    exit 1;
fi

# look for --dry-run and -R
refresh_flags="-b -z .old"
if echo "$*" | grep -q -e "--dry-run" -e '[[:blank:]]-R[[:blank:]]' ; then
    refresh_flags=
fi

# apply the patch and save the en_US messages
patch_log=`mktemp /tmp/defuzzypatch-log.XXXXXX`
LANG=en_US.UTF-8 patch "$@" $refresh_flags <$patch_file 2>&1 | tee $patch_log || exit 1;

if test -n "$refresh_flags" && grep -q "with fuzz" $patch_log ; then
    echo "Regenerating $patch_file..."
    patch_temp=`mktemp /tmp/defuzzpatch-diff.XXXXXX`
    IFS_old="$IFS"
    IFS='
'
    cd $dest_dir
    for file in `grep "^patching file" $patch_log | sed "s|^patching file ||"` ; do
	diff -puN "${file}".old "$file" >>$patch_temp
    done
    cd - >/dev/null 2>&1
    IFS="$IFS_old"
    mv "$patch_file" "${patch_file}".old
    mv $patch_temp "$patch_file"
    chmod 644 "$patch_file"
fi

rm $patch_log
