use Test::More tests => 10;
use Dpkg::IPC;

my $pwd = `pwd`;
chdir "t/extlinks_extcopies";
$ENV{PATH} = "../../tools:$ENV{PATH}";
spawn( exec => [ 'dh', 'build', '--with', 'nodejs' ], wait_child => 1 );

ok( -d 'node_modules',             'node_modules created' );
ok( -d 'node_modules/@types',      'node_modules/@types created' );
ok( -l 'node_modules/@types/node', '@types/node linked' );
spawn( exec => [ 'dh_auto_clean', '--buildsystem=nodejs' ], wait_child => 1 );
spawn( exec => ['dh_clean'],                                wait_child => 1 );
ok( !-e 'node_modules', 'node_modules removed' );

rename 'debian/nodejs/extlinks', 'debian/nodejs/extcopies';

spawn( exec => [ 'dh', 'build', '--with', 'nodejs' ], wait_child => 1 );
ok( -d 'node_modules',             'node_modules created' );
ok( -d 'node_modules/@types',      'node_modules/@types created' );
ok( -d 'node_modules/@types/node', '@types/node copied' );
spawn( exec => [ 'dh_auto_clean', '--buildsystem=nodejs' ], wait_child => 1 );
spawn( exec => ['dh_clean'],                                wait_child => 1 );
ok( !-e 'node_modules', 'node_modules removed' );

rename 'debian/nodejs/extcopies', 'debian/nodejs/extlinks';

# Regression test: an existing module flagged with "test" must be linked on a
# normal build but skipped when the nocheck build profile/option is set.
open my $fh, '>', 'debian/nodejs/extlinks';
print $fh "\@types/node  test\n";
close $fh;

# With nocheck: the test-flagged module must NOT be linked
{
    local $ENV{DEB_BUILD_PROFILES} = 'nocheck';
    spawn( exec => [ 'dh', 'build', '--with', 'nodejs' ], wait_child => 1 );
}
ok( !-e 'node_modules/@types/node',
    'test-flagged extlink skipped under nocheck' );
spawn( exec => [ 'dh_auto_clean', '--buildsystem=nodejs' ], wait_child => 1 );
spawn( exec => ['dh_clean'],                                wait_child => 1 );

# Without nocheck: the same module must be linked
spawn( exec => [ 'dh', 'build', '--with', 'nodejs' ], wait_child => 1 );
ok( -l 'node_modules/@types/node',
    'test-flagged extlink linked without nocheck' );
spawn( exec => [ 'dh_auto_clean', '--buildsystem=nodejs' ], wait_child => 1 );
spawn( exec => ['dh_clean'],                                wait_child => 1 );

# Restore the fixture to its original content
open $fh, '>', 'debian/nodejs/extlinks';
print $fh "\@types/node\n";
close $fh;
