#!/bin/bash

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

# initialize begin
DPT__SCRIPTS="/usr/share/pkg-perl-tools"
for f in ~/.dpt.conf ~/.config/dpt.conf; do
	if [ -r "$f" ]; then
		. "$f"
	fi
done
. "$DPT__SCRIPTS/lib/dpt-lib.sh"
# initialize end


[ -n "$PKG" ] && [ -n "$VER" ] && [ -n "$DIST" ] || \
	die "Source or Version or Distribution not set."

NEW=
while getopts n opt; do
	case $opt in
		n) NEW="--new";;
		*) ;;
	esac
done
shift $((OPTIND -1))

if git commit --dry-run -a > /dev/null ; then
	header "Release package"
	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

header "dgit push-source"
read -n 1 -p "dgit --gbp $NEW push-source? y/N " DGIT
if [ "$DGIT" = "y" ]; then
	echo
	dgit --gbp $NEW 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
				warn "'dgit --gbp --deliberately-not-fast-forward push-source' failed"
				warn "Maybe try 'dgit --gbp --overwrite push-source' after removing the tags …"
				exit 1
			fi
		fi
	fi
	if [ $? -eq 0 ]; then
		header "dpt push"
		read -n 1 -p "dpt push? y/N " DPT
		if [ "$DPT" = "y" ]; then
			echo
			dpt push
		fi

		EVER=$(echo "$VER" | sed -e 's/^[0-9]\+://')
		BUILDINFO=$(ls -rt1 ../{build-area/,}${PKG}_${EVER}_*.buildinfo 2>/dev/null | tail -n1)
		if [ -f "$BUILDINFO" ]; then
			header ".buildinfo"
			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
