#!/bin/bash
GIT_ARCHIVES="origin netz github"
if [ -s /etc/default/sourcemgr ]  ; then
. /etc/default/sourcemgr
fi

set -e
trap 'echo FAIL >&2' 0

if [ $(git ls-files --others --exclude-standard | wc -l) -gt 0 ] ; then
	echo "You have spurious files." >&2
	git ls-files --others --exclude-standard >&2
	exit 1
fi

TF=$(tempfile)
trap 'rm -f $TF; echo FAIL >&2' 0

if rev=$(git rev-parse deb 2>/dev/null) ; then
	comm=$(git merge-base deb HEAD)
	if [ $comm != $rev ] ; then
		echo "'deb' exists but is not my ancestor. Aborting." >&2
		exit 1
	fi
fi
if [ "$1" = "" -a $( (git diff --cached --name-only; git ls-files --modified --deleted --exclude-standard) | wc -l ) -eq 0 ] && git diff --name-only HEAD^ HEAD | fgrep -qs debian/changelog ; then
	echo "You have no uncommitted changes. Proceeding to build."
else
	if [ -z "$EMAIL" ] && ! grep -qs '^DEBEMAIL=' $HOME/.devscripts.conf ; then
		echo "(DEB)EMAIL muss gesetzt sein" >&2
		exit 1
	fi
	. $HOME/.devscripts.conf 
	export DEBEMAIL

	dist=$(dpkg-parsechangelog | sed -ne 's/^Distribution:.//p')

	mt=$(stat -c '%Y' debian/changelog)
	debchange -i --distribution $dist --force-distribution
	if [ $(stat -c '%Y' debian/changelog) = $mt ] ; then exit 1; fi

	dpkg-parsechangelog | sed -e '1,/^Changes:/d' |tail -n +3|sed -e 's/^   //' > $TF
	if test -d debian/.git ; then
		cd debian
	fi
	if [ "$1" = "-a" ] ; then
		git commit --amend -a -e -F $TF
	else
		git commit -a -e -F $TF
	fi

fi

trap 'echo FAIL >&2' 0

S=$(dpkg-parsechangelog | sed -ne 's/^Source: *//p')
V=$(dpkg-parsechangelog | sed -ne 's/^Version: *//p' | sed -e s/^42://)
CF=${S}_${V}_$(dpkg --print-architecture).changes
if [ -s ../$CF ] ; then
	echo "Changes file found. Not building."
else
	debuild -i -b -us -uc
fi
git branch -f deb # tested to be fast forward, above
git push-all
dput -u ext ../$CF

trap '' 0
echo OK
