#!/usr/bin/perl -w

=head1 NAME

dh_golang - Generates Built-Using substvar

=cut

use strict;
use Cwd qw(realpath);
use Debian::Debhelper::Dh_Lib; # not in core
use Dpkg; # not in core
use Dpkg::Control; # not in core
use Dpkg::Control::Info; # not in core
use Dpkg::Deps; # not in core
use Dpkg::Gettext; # not in core
use Scalar::Util qw(blessed); # in core since v5.7.3
use List::Util qw(first); # in core since v5.7.3
use Debian::Debhelper::Buildsystem::golang;

=head1 SYNOPSIS

B<dh_golang> [S<I<debhelper options>>]

=head1 DESCRIPTION

B<dh_golang> is a debhelper program which adds the misc:Built-Using substvar
based on the dependencies of the package being built. It uses go list to
determine the packages imported and dpkg-query to find the source package and
version that provided that package.

=head1 NOTES

The best way to invoke B<dh_golang> is by using B<dh --with=golang>.

=cut

init();

############################################################################
# Generate misc:Built-Using substvar.
############################################################################

my $bs = Debian::Debhelper::Buildsystem::golang->new();

$bs->_set_dh_gopkg();
$bs->_set_gopath();

my @targets = $bs->get_targets();

my $godeps = `go list -f '{{ range .Deps }}{{.}} {{ end }}' @targets`;
$godeps =~ s/\n/ /g;
my @godirs = split /\n/, `go list -f '{{ .Dir }}' $godeps`;
my $realgodirs;
my $cwd = $bs->{cwd};
for my $godir (@godirs) {
    my $realpath = realpath($godir);
    # @godirs will include the directories of the package being built, so exclude them.
    if ($realpath !~ /^$bs->{cwd}/) {
        $realgodirs .= realpath($godir) . " ";
    }
}
my $pkgs = `dpkg-query --search $realgodirs | cut -d: -f1`;
$pkgs =~ s/\n/ /g;
my $built_using = `dpkg-query -f='\${source:Package} (= \${source:Version}), ' -W $pkgs`;

# If there is an easier way to have a universal misc:Built-Using on all binary
# packages, I am happy to merge your patch :).
foreach my $package (@{$dh{DOPACKAGES}}) {
    addsubstvar($package, "misc:Built-Using", $built_using);
}

=head1 SEE ALSO

dh(1)

=head1 AUTHORS

Michael Stapelberg <stapelberg@debian.org>

=cut

# vim:ts=4:sw=4:et
