#!perl

use strict;
use warnings;

# This test was generated by inc::CheckJiraInChanges

use Test::More;

plan skip_all => "Disabled" if $ENV{NO_JIRA_CHECK};

my @commits = split /\n/, <<'EOC';
c40e1e14 (sandbox/master, origin/master, origin/HEAD) PERL-1127 Support Pipelines in BulkWriteView
3e1db167 PERL-1129 Apply TLS options from URI
9be7a7e5 PERL-1118 - Improve URI stringify sanitization
24f1f7c7 (shadowcat/staging) PERL-1121 - Fix BulkWriteResult inserted IDs
e554b859 PERL-1126 - Reset str to bool for URI options during SRV re-parsing
16b2782f PERL-1125 Use Num for expire time instead of Int
b17b7825 PERL-1081: Require retryable writes tests to run on mongos 4.2+

EOC

my %ticket_map;
for my $commit ( @commits ) {
    next if $commit =~ /PERL-\d+:?\s+CI:/i;
    for my $ticket ( $commit =~ /PERL-(\d+)/g ) {
        next if $ENV{CHECK_JIRA_SKIP}
            && grep { $ticket eq $_ } split " ", $ENV{CHECK_JIRA_SKIP};
        $ticket_map{$ticket} ||= [];
        push @{$ticket_map{$ticket}}, $commit;
    }
}

# grab Changes lines from new version to next un-indented line
open my $fh, "<:encoding(UTF-8)", "Changes";
my $changelog = do { local $/; <$fh> };

my @bad;
for my $ticket ( keys %ticket_map ) {
    if ( index( $changelog, "PERL-$ticket" ) < 0 ) {
       push @bad, $ticket;
    }
}

if ( !@commits ) {
    pass("No commits with Jira tickets");
}
else {
    ok( ! scalar @bad, "Jira tickets in Changes")
        or diag "Jira tickets missing:\n"
        . join("\n", map { "  * $_" } map { @{$ticket_map{$_}} } sort { $a <=> $b } @bad );
}

done_testing();
