#!perl
use Cassandane::Tiny;

#
# Test that
#  - cyr_expire archives messages
#  - once archived, messages are in the new path
#  - the message is gone from the old path
#  - XXX: hard to test - that there's no possible race in which the message
#    isn't available to clients during the archive operation
#
sub test_archive_messages
    :ArchivePartition :min_version_3_0
    ($self)
{
    my $talk = $self->{store}->get_client();
    $self->{store}->_select();
    $self->assert_num_equals(1, $talk->uid());
    $self->{store}->set_fetch_attributes(qw(uid flags));

    xlog $self, "Append 3 messages";
    my %msg;
    $msg{A} = $self->make_message('Message A');
    $msg{A}->set_attributes(id => 1,
                            uid => 1,
                            flags => []);
    $msg{B} = $self->make_message('Message B');
    $msg{B}->set_attributes(id => 2,
                            uid => 2,
                            flags => []);
    $msg{C} = $self->make_message('Message C');
    $msg{C}->set_attributes(id => 3,
                            uid => 3,
                            flags => []);
    $self->check_messages(\%msg);

    my $data = $self->{instance}->run_mbpath("-u", 'cassandane');
    my $datadir = $data->{data};
    my $archivedir = $data->{archive};

    $self->assert_file_test("$datadir/1.", "-f");
    $self->assert_file_test("$datadir/2.", "-f");
    $self->assert_file_test("$datadir/3.", "-f");

    $self->assert_not_file_test("$archivedir/1.", "-f");
    $self->assert_not_file_test("$archivedir/2.", "-f");
    $self->assert_not_file_test("$archivedir/3.", "-f");

    xlog $self, "Run cyr_expire but no messages should move";
    $self->{instance}->run_command({ cyrus => 1 }, 'cyr_expire', '-A' => '7d' );

    $self->assert_file_test("$datadir/1.", "-f");
    $self->assert_file_test("$datadir/2.", "-f");
    $self->assert_file_test("$datadir/3.", "-f");

    $self->assert_not_file_test("$archivedir/1.", "-f");
    $self->assert_not_file_test("$archivedir/2.", "-f");
    $self->assert_not_file_test("$archivedir/3.", "-f");

    xlog $self, "Run cyr_expire to archive now";
    $self->{instance}->run_command({ cyrus => 1 }, 'cyr_expire', '-A' => '0' );

    $self->assert_not_file_test("$datadir/1.", "-f");
    $self->assert_not_file_test("$datadir/2.", "-f");
    $self->assert_not_file_test("$datadir/3.", "-f");

    $self->assert_file_test("$archivedir/1.", "-f");
    $self->assert_file_test("$archivedir/2.", "-f");
    $self->assert_file_test("$archivedir/3.", "-f");
}
