#!/bin/bash
GIT_ARCHIVES=$(git config --get-regexp 'remote\...*\.push' | sort -u | sed -ne 's/^remote\.\([a-z]*\)\.push[= ].*/\1/p')
if [ -s /etc/default/sourcemgr ]  ; then
. /etc/default/sourcemgr
fi
if [ -z "$GIT_ARCHIVES" ] ; then
	echo "You have no archives. Refusing." >&2
	exit 1
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
touch $TF

for a in $GIT_ARCHIVES ; do
	git fetch $a && rm -f $TF
done
if [ -f $TF ] ; then
	echo "Could not reach any archive. Fix it." >&2
	exit 1
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 -S Distribution)

	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 -S Changes | tail -n +4 | sed -e 's/^  //' > $TF
	if [ "$1" = "-a" ] ; then
		git commit --amend -a -e -F $TF
	else
		git commit -a -e -F $TF
	fi
fi

for a in $GIT_ARCHIVES ; do
	git push $a && rm -f $TF
done

V=$(dpkg-parsechangelog -S Version | sed -e s/^42:// | sed -e 's/~/-/g')

git remote >$TF
for a in $GIT_ARCHIVES ; do
	git push $a && rm -f $TF
done
if [ -f $TF ] ; then
	echo "Could not push to any archive. Fix it." >&2
	exit 1
fi

rm -f $TF
trap 'echo FAIL >&2' 0

S=$(dpkg-parsechangelog -S Source)
V=$(dpkg-parsechangelog -S Version | sed -e s/^42:// | sed -e 's/~/-/g')
UV=$(echo $V | sed -e 's/-.*?//')
CF=${S}_${V}_$(dpkg --print-architecture).changes
if [ -s ../$CF ] ; then
	echo "Changes file found. Not building."
else
	debuild -i -b -us -uc -j$(( $(grep "^processor.*:" /proc/cpuinfo|wc -l) / 2 + 1))
	for a in $GIT_ARCHIVES ; do
		git push --tags $a || true
	done
fi
dput -u ext ../$CF

trap '' 0
echo OK
