#!/bin/sh

if git diff-index --quiet HEAD --; then
	git fetch --all # -or- git fetch <upstream repo>
else
	echo working directory not clean. exiting.
	exit 1
fi

tag=$(git tag -l|grep ^v[0-9]|tail -n1)
ver=$(echo $tag|sed s/^v//)
dstag=upstream/${ver}+ds
rmfiles=$(grep "Files-Excluded:" debian/copyright|sed s/Files-Excluded://)
git merge $tag

for i in $rmfiles; do if [ "$i" != "debian" ]; then git rm -rf "$i"; fi; done
git checkout HEAD debian/

if git diff-index --quiet HEAD --; then
	git commit --amend -m "Merge upstream tag: $tag"
else
	git commit -m "Merge upstream tag: $tag"
fi

git rm -qrf debian/
git commit -m "pristine source of ${ver}+ds"
if git rev-parse -q --verify "refs/tags/${dstag}" >/dev/null; then
	echo skipping tag current commit as "${dstag}", due to it exists already.
	exit 0
fi

git tag ${dstag}
git reset --hard HEAD^

echo
echo if you need to remove more files, do it now then run script to update the ds tag:
printf \\tdebian/maint-tools/update_ds_tag\\n
