#!/usr/bin/perl -w

=head1 NAME

dh_makegolangshlibs - Generates golang-specific shlibs files and substvars

=cut

use strict;
use Debian::Debhelper::Dh_Lib;
use File::Find;
use MIME::Base64;

=head1 SYNOPSIS

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

=head1 DESCRIPTION

B<dh_makegolangshlibs> is a debhelper program which generates a
substvar and shlibs file to enable packages depending on go shared
libraries to conveniently depend on the ABI hash of the library rather
than just the soversion.  It replaces dh_makeshlibs in the usual dh
sequences.

=head1 NOTES

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

=cut

init();

############################################################################
# Generate ...
############################################################################

my ($libpkg, $devpkg, $libname, $sover);

foreach my $pkg (@{$dh{DOPACKAGES}}) {
    if ($pkg =~ /^lib(golang.*?)-?([0-9]+)$/) {
        $libpkg = $pkg;
        $libname = $1;
        $sover = $2;
    }
    if ($pkg =~ /-dev$/) {
        $devpkg = $pkg;
    }
}

if (!defined($libpkg)) {
    exit(0);
} elsif (!defined($devpkg)) {
    printf("found lib package but not dev");
    exit(1);
}

my $sofile = sprintf(
    "%s/usr/lib/%s/lib%s.so.%s",
    tmpdir($libpkg), dpkg_architecture_value("DEB_HOST_MULTIARCH"),
    $libname, $sover);

my $gccgo;
if (system("go tool -n compile > /dev/null 2>&1") == 0) {
    $gccgo = 0;
} else {
    $gccgo = 1;
}
my $hexhash = "";
if ($gccgo) {
    open(my $fh, "-|", "bash -c 'objcopy --dump-section .go_export=>(cat) $sofile'");
    while (<$fh>) {
        if (/^checksum ([A-Z0-9]+)/) {
            $hexhash = $1;
        }
    }
    close($fh);
} else {
    $hexhash=`/usr/lib/go/pkg/readabihash $sofile`;
}
chomp($hexhash);
if ($hexhash eq "") {
    die "could not compute hash of $sofile";
}

my $libpkgdir=tmpdir($libpkg);
if (! -d "$libpkgdir/DEBIAN") {
    doit("install","-d","$libpkgdir/DEBIAN");
}
my $provides = "$libpkg-$hexhash";
addsubstvar($libpkg, "golang:Provides", $provides);
complex_doit("echo 'lib$libname $sover $provides' >$libpkgdir/DEBIAN/shlibs");
doit("chmod",644,"$libpkgdir/DEBIAN/shlibs");
doit("chown","0:0","$libpkgdir/DEBIAN/shlibs");
autotrigger($libpkg, 'activate-noawait', 'ldconfig');

=head1 SEE ALSO

dh(1)

=head1 AUTHORS

Michael Hudson-Doyle <michael.hudson@canonical.com>

=cut

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