#!/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 Debian::Debhelper::Dh_Buildsystems; # not in core
use File::Temp qw(tempdir);
use File::Path qw(rmtree);

=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

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

buildsystems_init();
my $bs = load_buildsystem("golang");

$bs->_set_gopath();

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

my $tmpl = '{{ range .Deps }}{{.}}
{{ end }}';

my $tmpdir = tempdir("dh_golang_XXXXXXX", TMPDIR => 1);

system("go list -f \"$tmpl\" @targets > $tmpdir/godeps") == 0
    or die "go list of targets failed with code $?, $!";

my $gofiletmpl = '\
{{ .Dir }}/{{ index (or .GoFiles .CgoFiles .TestGoFiles .XTestGoFiles .IgnoredGoFiles) 0 }}';

system("sort -u $tmpdir/godeps | xargs go list -f '$gofiletmpl' > $tmpdir/gofiles") == 0
    or die "go list of dependencies failed with code $?, $!";

open(my $inp, "<", "$tmpdir/gofiles");
open(my $outp, ">", "$tmpdir/realgofiles");
while (<$inp>) {
    chomp;
    my $realpath = realpath($_);
    # gofiles will include packages being built, so exclude those.
    if ($realpath !~ /^\Q$bs->{cwd}\E/) {
        printf $outp "%s\n", $realpath;
    }
}
close($inp);
close($outp);

system("cat $tmpdir/realgofiles | xargs -r dpkg-query --search > $tmpdir/pkgs") == 0
    or die "dpkg-query --search failed with code $?, $!";

system("cut -d: -f1 $tmpdir/pkgs | sort -u | xargs -r dpkg-query -f='\${source:Package} (= \${source:Version})\n' -W > $tmpdir/srcpkgs");
if ($? != 0) {
    die "dpkg-query -W failed with code $?, $!";
}

my $built_using = `cat $tmpdir/srcpkgs | sort -u`;

$built_using =~ s/\n/, /g;

rmtree($tmpdir);

# 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
