# pkg-js/no-testsuite -- lintian check script for detecting a bad debian/watch configuration

package Lintian::Check::PkgJs::Repo;

use strict;
use warnings;
use Dpkg::IPC;
use Moo;
use namespace::clean;

with 'Lintian::Check';

sub source {
    my ($self) = @_;
    my ( $out, $err );
    $self->pkgjsScan('debian/build_modules');
    $self->pkgjsScan('debian/tests/test_modules');
    return unless ( -e 'package.json' );
    spawn(
        exec            => ['debcheck-node-repo'],
        to_string       => \$out,
        error_to_string => \$err,
        wait_child      => 1,
        nocheck         => 1
    );
    $self->hint('inconsistency-debian-watch') if $?;
}

sub pkgjsScan {
    my ( $self, $dir, $prefix ) = @_;
    return unless -d $dir;
    $prefix //= '';
    my $dh;
    opendir $dh, $dir;
    map {
        if ( !-d "$dir/$_" or /^\./ ) {
        }
        elsif (/^\@/) {
            pkgjsScan( "$dir/$_", $_ );
        }
        else {
            my $out;
            my $module_name = ( $prefix ? "$prefix/" : '' ) . $_;
            print STDERR "$module_name\n";
            spawn(
                exec       => [ 'apt-file', 'search', "/nodejs/$module_name/" ],
                nocheck    => 1,
                wait_child => 1,
                to_string  => \$out,
            );
            if ( !$@ and $out ) {
                $self->hint( 'embedded-module-which-exists-in-debian',
                    $module_name, $dir );
            }
        }
    } readdir $dh;
    closedir $dh;
}

1;
