#!/usr/bin/perl

use strict;
use warnings;

use Debian::Debhelper::Dh_Lib;
use Path::Tiny;

=head1 NAME

dh_raku_build -- automatically build Raku module packages

=head1 SYNOPSIS

B<dh_raku_build>

=head1 DESCRIPTION

This script will call C<prove6 -l -v> to self-build a Raku module package. It will
only do so if three conditions are met:

=over

=item *

A 't' directory exists

=item *

raku-tap-harness is installed, typically by adding it to the build-depencies
of the package being built

=item *

The debhelper build option 'nocheck' is not set

=back

=head1 SEE ALSO

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

=cut

init();

foreach my $pkg (getpackages()) {
    nonquiet_print("Checking installation of $pkg");
    my $tmp = path(tmpdir($pkg));
    my $precomp = path('debian/tmp/pre-compiled');
    die "Cannot find pre-compiled files\n" unless $precomp->is_dir;
    my $perl6_path = $tmp->child("usr/lib/perl6");
    my $iter = $precomp->iterator({ recurse => 1 });

    my $vendor = $perl6_path->child("vendor");

    my @to_do;
    my @installed;
    while (my $path = $iter->()) {
        my $subpath = $path->relative($precomp);
        my $target = $vendor->child($subpath);
        push @to_do, sub {
            # skip directories
            if ($path->is_dir and $path->children) {
                $target->mkpath(mode => oct(755));
            }
            elsif ($path->is_file) {
                nonquiet_print("Installing $path in $target");
                push @installed, $subpath;
                install_file ($path->stringify, $target->stringify);
            }
        };
    }

    # list pre-compiled files to let rakudo-helper know that these
    # pre-compiled files are shipped with the package.
    # can be removed once debian 13 is out
    push @to_do, sub {
        my $file_name = "$pkg.dh-raku.list";
        my $list = $precomp->child($file_name);
        $list->spew(map {"$_\n"} @installed);
        nonquiet_print("Installing $file_name in $vendor");
        install_file ($list->stringify, $vendor->child($file_name)->stringify);
    };

    log_installed_files($pkg, $precomp->stringify);

    next unless process_pkg($pkg);

    nonquiet_print("Installing $pkg");
    foreach my $sub (@to_do) {
        $sub->();
    }
}
