#!perl
use Cassandane::Tiny;

sub test_quota_f_nested_qr
    :NoAltNameSpace
{
    my ($self) = @_;

    xlog $self, "Test that quota -f correctly calculates the STORAGE quota";
    xlog $self, "with a nested quotaroot and a folder whose name sorts after";
    xlog $self, "the nested quotaroot [Bug 3621]";

    my $inbox = "user.cassandane";
    # These names are significant - we need subfolders both before and
    # after the subfolder on which we will set the nested quotaroot
    my @folders = ( $inbox, "$inbox.aaa", "$inbox.nnn", "$inbox.zzz" );

    xlog $self, "add messages to use some STORAGE quota";
    my %exp;
    my $n = 5;
    foreach my $f (@folders)
    {
        $self->{store}->set_folder($f);
        for (1..$n) {
            my $msg = $self->make_message("$f $_",
                                          extra_lines => 10 + rand(5000));
            $exp{$f} += length($msg->as_string());
        }
        $n += 5;
        xlog $self, "Expect " . $exp{$f} . " on " . $f;
    }

    xlog $self, "set a quota on inbox";
    $self->_set_limits(quotaroot => $inbox, storage => 100000);

    xlog $self, "should have correct STORAGE quota";
    my $ex0 = $exp{$inbox} + $exp{"$inbox.aaa"} + $exp{"$inbox.nnn"} + $exp{"$inbox.zzz"};
    $self->_check_usages(quotaroot => $inbox, storage => int($ex0/1024));

    xlog $self, "set a quota on inbox.nnn - a nested quotaroot";
    $self->_set_limits(quotaroot => "$inbox.nnn", storage => 200000);

    xlog $self, "should have correct STORAGE quota for both roots";
    my $ex1 = $exp{$inbox} + $exp{"$inbox.aaa"} + $exp{"$inbox.zzz"};
    my $ex2 = $exp{"$inbox.nnn"};
    $self->_check_usages(quotaroot => $inbox, storage => int($ex1/1024));
    $self->_check_usages(quotaroot => "$inbox.nnn", storage => int($ex2/1024));

    xlog $self, "create a bogus quota file";
    $self->_zap_quota(quotaroot => $inbox);
    $self->_zap_quota(quotaroot => "$inbox.nnn");
    $self->_check_usages(quotaroot => $inbox, storage => 0);
    $self->_check_usages(quotaroot => "$inbox.nnn", storage => 0);

    xlog $self, "run quota -f to find and add the quota";
    $self->{instance}->run_command({ cyrus => 1 }, 'quota', '-f');

    xlog $self, "check that STORAGE quota is restored for both roots";
    $self->_check_usages(quotaroot => $inbox, storage => int($ex1/1024));
    $self->_check_usages(quotaroot => "$inbox.nnn", storage => int($ex2/1024));

    xlog $self, "run quota -f again";
    $self->{instance}->run_command({ cyrus => 1 }, 'quota', '-f');

    xlog $self, "check that STORAGE quota is still correct for both roots";
    $self->_check_usages(quotaroot => $inbox, storage => int($ex1/1024));
    $self->_check_usages(quotaroot => "$inbox.nnn", storage => int($ex2/1024));
}
