#!/bin/bash
set -x

# extract all of the changesets since the last tagged version and put them
# into debian/patche{s,d} as if this was a patched tree on that tag

TARGET="$1"

ver=$(git describe --match [0-9v]\* --tags)
if [[ $ver = *-*-* ]]; then
	hash=${ver##*-}
	ffw=${ver#*-}
	ffw=${ffw%-*}
	ver=${ver%%-*}
fi
if [ $ffw -gt 0 ]; then
	tag=$ver
	if [[ $ver =~ ^v([0-9]+_)+([0-9]+|RC[0-9]+)$ ]]; then
		ver=$(echo $ver |
		  sed -e 's/^v\(.*\)/\1/' \
		      -e 's/_RC[0-9].*$//' \
		      -e 's/_/./g')
	fi
	pdir="$TARGET/debian/patches"
	if [ -d $pdir ]; then
		rm -rf $pdir
	fi
	mkdir $pdir
	git format-patch -o $pdir $tag..HEAD
	pushd $pdir
	if [ -d ../patched ]; then
		rm -rf ../patched
	fi
	mkdir ../patched
	rm -f 00list *.dpatch
	for file in [0-9][0-9][0-9][0-9]-*.patch; do
		if [ -s $file ] && ! grep -q "^--- a/debian/" $file; then
			# remove patching of files that the debian packaging
			# should not be touching
			ed <<EOF $file
/diff --git a\/local-env.sh b\/local-env.sh
/diff --git a\//i
endofrangemarker
.
?diff --git a\/
/diff --git a\/local-env.sh b\/local-env.sh/,/endofrangemarker/d
w
q
EOF
			desc=$(cat $file | sed -e '1,/^$/d' \
					       -e '/^---$/,$d')
			dpatch_file=${file/.patch/.dpatch}
			sed -e '1,/^---$/d' $file | \
			  dpatch patch-template -p "${file%.patch}" \
			  "$desc" > $dpatch_file
			echo "faked by make debs run from git" > \
			  ../patched/$dpatch_file
			echo $dpatch_file >> 00list
		fi
		rm -f $file
	done
fi
