#!/bin/sh

# copyright, licensing and documentation at the end

set -e
set -u

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

warn() {
	echo "$1" >&2
}

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

if ! git remote show | grep -qx upstream-repo ; then
	warn "git remote 'upstream-repo' not found, trying to add it ..."

	# case 1: Git URL in d/copyright's Source paragraph
	REPO=$(perl -MDebian::Copyright -E '$c = Debian::Copyright->new(); $c->read("debian/copyright"); say $c->header()->Source' | grep -oE "git(?:+ssh)?:.+$" || true)

	# case 2: Repository in d/upstream
	if [ -z "$REPO" -a ! -e debian/upstream ] ; then
		warn "No 'debian/upstream' file found, trying to create it ..."
		dpt debian-upstream || true
		if [ -e debian/upstream ] ; then
			git add debian/upstream
			git commit -m "Add debian/upstream"
		fi
	fi
	if [ -z "$REPO" -a -e debian/upstream ] ; then
		REPO=$(awk '/^Repository:.*git(\+ssh)?:.+/ {print $2;}' debian/upstream || true)
	fi

	if [ -n "$REPO" ] ; then
		warn "Adding Git remote 'upstream-repo' with URL '$REPO' ..."
		git remote add upstream-repo "$REPO"
	else
		warn "No upstream Git URL found in 'debian/copyright' or 'debian/upstream'. Run 'git remote add upstream-repo <URL>' manually to track upstream."
	fi
else
	warn "Found git remote 'upstream-repo':"
	git remote --verbose show upstream-repo
fi

POD=<<'EOF'
=head1 NAME

dpt-upstream-repo - add upstream Git repository as git remote upstream-repo

=head1 SYNOPSIS

B<dpt upstream-repo>

=head1 DESCRIPTION

B<dpt upstream-repo> adds the upstream Git repository as a B<git remote>
named I<upstream-repo>. The URL for the repository is read from either
F<debian/copyright>'s I<Source> field or from F<debian/upstream>'s
I<Repository> field.

In case there's no Git URL in F<debian/copyright> and F<debian/upstream>
doesn't exist, the latter is created with L<dpt-debian-upstream(1)>.

=head1 SEE ALSO

L<dpt-debian-upstream(1)>

=head1 COPYRIGHT & LICENSE

=over

=item Copyright 2013 gregor herrmann L<gregoa@debian.org>

=back

This program is free software, licensed under the same term as perl.

=cut
EOF
