#!/bin/sh

# copyright, licensing and documentation at the end

set -e
set -u

usage() {
    perl -MPod::Usage=pod2usage -e"pod2usage(-input => '$0', -verbose=>99, -sections=>[qw(SYNOPSIS DESCRIPTION COMMANDS)])"
    exit 1
}


[ -n "${1:-}" ] || usage

cd "${DPT_PACKAGES:=.}"
for pkg in "$@"; do
    if [ -d "$pkg" ]; then
        echo "Updating existing checkout in ${DPT_PACKAGES}/$pkg"
        cd "$pkg"
        gbp pull --pristine-tar
        git fetch origin refs/notes/commits:refs/notes/commits >|/dev/null 2>&1 || true
        cd - > /dev/null
    else
        gbp clone --all "git@salsa.debian.org:perl-team/modules/packages/$pkg.git"
        cd "$pkg"
        git fetch origin refs/notes/commits:refs/notes/commits >|/dev/null 2>&1 || true

        echo "$pkg ready in ${DPT_PACKAGES}/$pkg"
    fi

    METADATA="$DPT_PACKAGES/$pkg/debian/upstream/metadata"
    if [ -e "$METADATA" ] ; then
        REPO=$(awk '/Repository:/ { print $2 }' "$METADATA")
        if [ -n "$REPO" ]; then
            (
                cd "$DPT_PACKAGES/$pkg"
                if git remote show upstream-repo > /dev/null 2>&1 ; then
                    git fetch upstream-repo
                else
                    dpt upstream-repo
                fi
            ) || true
        fi
    fi
done

exit 0

POD=<<'EOF'
=head1 NAME

dpt-checkout - work on a pkg-perl package

=head1 SYNOPSIS

B<dpt checkout> I<package-name> [I<package-name> ...]

B<dpt co> I<package-name> [I<package-name> ...]

=head1 DESCRIPTION

B<dpt checkout> checks out a working copy for the packaging of a given package.

If you use L<dpt-shell-lib(1)>, B<dpt checkout> even puts you in the
directory of working copy if you checked out only one source package.

If the package directory exists, the clone is updated by calling
L<gbp-pull(1)>. If it doesn't exist, it is cloned off pkg-perl git
repositories via L<gbp-clone(1)>.

If there is an upstream repository information in F<debian/upstream/metadata>,
L<dpt-upstream-repo(1)> is invoked to add it as a Git remote.

B<dpt co> is an alias for B<dpt checkout>.

=head1 CONFIGURATION

B<dpt checkout> uses the C<DPT_PACKAGES> environment variable. If
C<DPT_PACKAGES> is not defined, the current working directory is used.

See L<dpt-config(5)> for details.

=head1 COPYRIGHT & LICENSE

=over

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

=item Copyright 2013, 2014 Damyan Ivanov L<dmn@debian.org>

=item Copyright 2013 Axel Beckert L<abe@debian.org>

=back

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

=cut
EOF
