#!/usr/bin/perl

use strict;
use warnings;
use Cwd qw/getcwd/;

use Debian::Debhelper::Dh_Lib;

=head1 NAME

dh_raku_build -- automatically build Raku module packages

=head1 SYNOPSIS

B<dh_raku_build>

=head1 DESCRIPTION

This script calls C<install-dist.p6> to build a Raku module package.

Then it injects rakudo dependencies information in C<${raku:Depends}>
variable.

In other word, your control file B<must> have a line like:

    Depends: ${raku:Depends}

=head2 HOME directory

Before building the package, the C<HOME> directory is set to
C<debian/tmp/home>. This directory is cleaned up after the build is
done.

=head1 SEE ALSO

L<debhelper>(7), L<dh>(1)

=cut

init();

foreach my $pkg (getpackages()) {
    nonquiet_print("Pre-compiling $pkg");

    my $tmp_home = getcwd."/debian/tmp/home/";
    my $installer = '/usr/share/perl6/tools/install-dist.raku';

    if (not -e $installer) {
        # use old installer
        $installer =~ s/raku/p6/;
    }

    my $pre_comp_dir= getcwd."/debian/tmp/pre-compiled/";
    my @cmd = (
        qw!raku!, $installer,
        qw!--for=vendor --from=.!,
        "--to=".$pre_comp_dir
    );

    print_and_doit({
        update_env => {
            HOME => $tmp_home,
            RAKUDO_RERESOLVE_DEPENDENCIES => 0,
            RAKUDO_LOG_PRECOMP => 1,
            # remove this variable when all precomp problem are solved.
            RAKUDO_MODULE_DEBUG => 1,
            RAKULIB => "inst#".$pre_comp_dir
        }
    },@cmd);

    # clean up
    doit(qw!rm -rf!, $tmp_home);

    open(my $rakudo, '-|', 'raku -V') or die "Couldn't open a pipe into raku: $!";
    my $raku_version;
    while (my $line = <$rakudo>) {
        if ($line =~ /^Raku::version=([\d.]+)$/) {
            $raku_version = $1;
        }
    }

    die "Could not find raku version from 'raku -V' output\n" unless defined $raku_version;

    # find the compiler id of raku truncated to 8 chars (like in rakudo's rules file)
    my $comp_version = `rakudo-m -e 'print substr(\$*PERL.compiler.id.lc,0,8)'`;

    addsubstvar($pkg, 'raku:Depends', "raku-api-$raku_version+$comp_version");
}
