#!perl
use Cassandane::Tiny;

sub test_dedup_part_index
    :min_version_3_3
{
    my ($self) = @_;

    my $xapdirs = ($self->{instance}->run_mbpath(-u => 'cassandane'))->{xapian};

    $self->make_message('msgA', body => 'part1') || die;
    $self->make_message('msgB', body => 'part2') || die;

    xlog "create duplicate part within the same indexing batch";
    $self->make_message('msgC', body => 'part1') || die;
    $self->{instance}->run_command({cyrus => 1}, 'squatter');

    xlog "create duplicate part in another indexing batch";
    $self->make_message('msgD', body => 'part1') || die;
    $self->{instance}->run_command({cyrus => 1}, 'squatter', '-i');

    xlog "assert deduplicated parts";
    my $delveout = $self->run_delve($xapdirs->{t1} . '/xapian', '-V0');
    $delveout =~ s/^Value 0 for each document: //;
    my @docs = split ' ', $delveout;
    my @parts = map { $_ =~ /^\d+:\*P\*/ ? substr($_, 5) : () } @docs;
    my @gdocs = map { $_ =~ /^\d+:\*G\*/ ? substr($_, 5) : () } @docs;
    $self->assert_num_equals(2, scalar @parts);
    $self->assert_str_not_equals($parts[0], $parts[1]);
    $self->assert_num_equals(4, scalar @gdocs);

    xlog "compact to t2 tier";
    $self->{instance}->run_command({cyrus => 1}, 'squatter', '-z', 't2', '-t', 't1');

    xlog "create duplicate part in top tier";
    $self->make_message('msgD', body => 'part1') || die;
    $self->{instance}->run_command({cyrus => 1}, 'squatter', '-i');

    xlog "Assert deduplicated parts across tiers";
    $delveout = $self->run_delve($xapdirs->{t1}. '/xapian.1', '-V0');
    $delveout =~ s/^Value 0 for each document: //;
    @docs = split ' ', $delveout;
    @parts = map { $_ =~ /^\d+:\*P\*/ ? substr($_, 5) : () } @docs;
    @gdocs = map { $_ =~ /^\d+:\*G\*/ ? substr($_, 5) : () } @docs;
    $self->assert_num_equals(0, scalar @parts);
    $self->assert_num_equals(1, scalar @gdocs);
}
