#!/bin/sh
# This script reads a list of revision ranges suitable for git format-patch
# from the file debian/git-patches, one per line, and exports them to the
# debian/patches directory in a form suitable for format 3.0(quilt) packages.
# It is not required for creating such packages, but permits you to separate
# out individual patches from what would otherwise be just a single blob.
#
# The revision ranges may include $DEB_VERSION and/or $UPSTREAM_VERSION, which
# will be substituted according to the version of the package being exported.
#
# To enable this hook, use:
# git config gitpkg.deb-export-hook /usr/share/gitpkg/hooks/quilt-patches-deb-export-hook

patch_list=debian/git-patches

if [ ! -r "$patch_list" ]; then
    echo "No $patch_list file, I guess you've pushed them all upstream."
    echo "Good Work!"
    exit 0
fi


if [ -n "$REPO_DIR" ]; then
    git_dir="--git-dir \"$REPO_DIR/.git\""
else
    # support running as a free-standing script, without gitpkg
    DEB_VERSION="$(dpkg-parsechangelog | sed -rne 's/^Version: ([^:]+:)?//p')"
fi;


UPSTREAM_VERSION="${DEB_VERSION%-*}"

tmpdir=$(mktemp -d patches.XXXXXXX)
count=1

# counting lines relies on this one being there.
echo "# Patches exported from git by gitpkg-export-patches" > $tmpdir/series

do_patches (){
    while read -r line
    do
	[ -n "$line" ] || continue
	case $line in
	    \#*)
		;;
	    *)
		if PATCHES="$(git $git_dir format-patch --start-number $count -N -o $tmpdir "$line")"; then
		    echo "$PATCHES" | sed -e "s,$tmpdir/,,g" -e 's, ,\n,g'>> $tmpdir/series
		    count=$(wc -l $tmpdir/series | cut -f1 -d' ')
		else
		    echo "git $git_dir format-patch --start-number $count -N -o $tmpdir $line"
		    echo "failed."
		    exit 1
		fi
	esac
    done
}

sed -e "s/\$DEB_VERSION/$DEB_VERSION/g"			\
    -e "s/\${DEB_VERSION}/$DEB_VERSION/g"		\
    -e "s/\$UPSTREAM_VERSION/$UPSTREAM_VERSION/g"	\
    -e "s/\${UPSTREAM_VERSION}/$UPSTREAM_VERSION/g"	\
    < "$patch_list" | do_patches || exit 1

if [ $count -gt 0 ]; then
    rm -rf debian/patches
    mv $tmpdir debian/patches
else
    echo "No patches found: debian/patches left untouched"
    #XXX well, except we already mashed the series file ...
    #     so what should we do here?  it's not really an error to have no patches
fi
