#!/usr/bin/perl

use strict;
use warnings;

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

=head1 NAME

dh_raku_install -- automatically install Raku module packages

=head1 SYNOPSIS

B<dh_raku_install>

=head1 DESCRIPTION

This script installs files prepared by L<dh_raku_build> in
C<debian/tmp> directory.

=head1 SEE ALSO

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

=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 $bin_path = $tmp->child("usr/bin");
    my $iter = $precomp->iterator({ recurse => 1 });

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

    my @to_do;
    my @installed;
    while (my $path = $iter->()) {
        next unless $path->is_file;

        my $subpath = $path->relative($precomp);
        my $target = $vendor->child($subpath);
        my $todo_sub;

        if ($path->parent->basename eq 'bin') {
            if ($path !~ /-(j|js|m)$/) {
                $todo_sub = sub {
                    my $bin_target = $bin_path->child($path->basename);
                    $bin_path->mkpath(mode => oct(755));
                    verbose_print("Installing bin $path in $bin_target");
                    $path->edit_utf8(sub { s(^#!/usr/bin/env rakudo)(#!/usr/bin/raku); });
                    push @installed, $subpath;
                    install_file ($path->stringify, $bin_target->stringify);
                };
            }
        }
        else {
            $todo_sub = sub {
                verbose_print("Installing $path in $target");
                $target->parent->mkpath(mode => oct(755));
                push @installed, $subpath;
                install_file ($path->stringify, $target->stringify);
            };
        }

        push @to_do, $todo_sub if $todo_sub;
    }

    # 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"} sort @installed);
        verbose_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 package files");
    foreach my $sub (@to_do) {
        $sub->();
    }
}
