#!/bin/bash

# Copyright 2019-2021, gregor herrmann <gregoa@debian.org>
# Released under the WTFPL

die() {
	echo "$1" >&2
	exit 1
}

dh_testdir || die "Not a source package …"

PKG=$(dpkg-parsechangelog -S Source)
VER=$(dpkg-parsechangelog -S Version)
DIST=$(dpkg-parsechangelog -S Distribution)
[ -n "$PKG" ] && [ -n "$VER" ] && [ -n "$DIST" ] || \
	die "Source or Version or Distribution not found in debian/changelog."

if git commit --dry-run -a > /dev/null ; then
	git add debian/changelog
	git commit -m "releasing package $PKG version $VER into distribution $DIST" -m 'Gbp-Dch: Ignore'
fi

if git commit --dry-run -a > /dev/null ; then
	die "git tree dirty …"
fi

read -n 1 -p "dgit --gbp push-source? y/N " DGIT
if [ "$DGIT" = "y" ]; then
	echo
	dgit --gbp push-source
	if [ $? -ne 0 ]; then
		read -n 1 -p "dgit --gbp --deliberately-not-fast-forward push-source? y/N " DGIT1
		if [ "$DGIT1" = "y" ]; then
			echo
			dgit --gbp --deliberately-not-fast-forward push-source
			if [ $? -ne 0 ]; then
				echo
				echo "'dgit --gbp --deliberately-not-fast-forward push-source' failed"
				echo "Maybe try 'dgit --gbp --overwrite push-source' after removing the tags ..."
				exit 1
			fi
		fi
	fi
	if [ $? -eq 0 ]; then
		read -n 1 -p "dpt push? y/N " DPT
		if [ "$DPT" = "y" ]; then
			echo
			dpt push
		fi

		VER=$(echo "$VER" | sed -e 's/^[0-9]\+://')
		BUILDINFO=$(ls -rt1 ../{build-area/,}${PKG}_${VER}_*.buildinfo 2>/dev/null | tail -n1)
		if [ -f "$BUILDINFO" ]; then
			read -n 1 -p "upload .buildinfo to buildinfo.d.n? y/N " BIUP
			if [ "$BIUP" = "y" ]; then
				echo
				if ! grep -q "BEGIN PGP SIGNATURE" "$BUILDINFO" ]; then
					debsign --no-re-sign "$BUILDINFO"
				fi
				curl -X PUT --max-time 30 --data-binary @${BUILDINFO} https://buildinfo.debian.net/api/submit
			fi
		fi
	fi
fi
