#!/bin/sh

# Copyright & License below

set -e
set -u

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

dh_testdir  || die "This doesn't look like a source package directory."
[ -d .git ] || die "No .git directory found."

INTERACTIVE=
GITIGNORE=

while getopts i OPTS; do
	case "$OPTS" in
		i) INTERACTIVE=1;;
		*) ;;
	esac
done
shift $(expr $OPTIND - 1)

if [ -f .gitignore ]; then
	INTERACTIVE=1
	GITIGNORE=1
fi

BASETAG=${1:-}
[ -n "$BASETAG" ] || die "Base tag needed."
NEWVERSION=${2:-}
[ -n "$NEWVERSION" ] || die "New version needed"

TEMPBRANCH="dpt-$(basename $0)-$$"
trap "git branch --delete --force $TEMPBRANCH" QUIT TERM EXIT

PKG=$(dpkg-parsechangelog --show-field Source)

git branch $TEMPBRANCH $BASETAG
gbp import-dsc --debian-branch $TEMPBRANCH apt:$PKG=$NEWVERSION
ENCODEDVERSION=$(echo $NEWVERSION | sed -e 's/:/%/' -e 's/~/_/')

if [ -z "$INTERACTIVE" ]; then
	git merge --no-edit debian/$ENCODEDVERSION
else
	git merge --no-commit debian/$ENCODEDVERSION
	if [ -n "$GITIGNORE" ]; then
		echo "I: Trying to recover .gitignore ..."
		git reset -- .gitignore; git co -- .gitignore
	fi
	echo "I: Do any manual fixup before running"
	echo "I: git merge --continue"
fi

exit 0

POD=<<'EOF'
=head1 NAME

dpt-missing-upload -- incorporate package uploads not done from Git

=head1 SYNOPSIS

B<dpt missing-upload> [B<-i>] I<BASETAG> I<NEWVERSION>

=head1 DESCRIPTION

B<dpt missing-upload> incorporates uploads of a package which are not yet in
the Git repo, e.g. NMUs.

To be run in the root directory of the source package's Git repo, and with
the target branch checked out.

=head1 OPTIONS

Options must come before parameters.

=over

=item B<-i>

Run interactively, e.g. call C<git merge> with I<--no-commit>, so the commit
can be amended. Useful if the imported upload adds/removes files.

Interactive mode is also enabled if a F<.gitignore> file is found.

=back

=head1 PARAMETERS

=over

=item BASETAG

The Git tag representing the package version before the one to be imported. Required.

=item NEWVERSION

The package version to be downloaded and imported. Required.

=back

=head1 NOTES

=over

=item

To make merging Debian tags as painless as possible, L<dpkg-mergechangelogs(1)> is helpful.

=item

For downloading the source package, C<deb-src> entries are required in the F<sources.list>.

=back

=head1 COPYRIGHT & LICENSE

Copyright: 2020-2021, gregor herrmann E<lt>gregoa@debian.orgE<gt>

License: Artistic | GPL-1+

=cut
EOF
