#!perl
use Cassandane::Tiny;
use Cassandane::Net::FakeManageSieve;

sub test_managesieve_referral_callbacks
    ($self)
{
    my $srv = Cassandane::Net::FakeManageSieve->new(
        refer => {
            LISTSCRIPTS => sub ($srv, @) {
                my $port = $srv->port('target');
                qq{BYE (REFERRAL "sieve://127.0.0.1:$port") "moved"\r\n};
            },
        },
        target => {
            auth => sub ($authzid, $authcid, $password) {
                "$authzid/$authcid/$password" eq 'user/auth/secret'
                    ? "OK\r\n" : qq{NO "bad credentials"\r\n};
            },
            LISTSCRIPTS => sub { qq{"s1" ACTIVE\r\nOK\r\n} },
        },
    );

    # The callbacks are only referenced by the handle once the call
    # returns, and are called again when following the referral.
    my ($status, $out) = $srv->run_client($self->{instance}, <<'EOF', $srv->port('refer'));
my ($port) = @ARGV;
my %creds = (username => 'user', authname => 'auth', password => 'secret');
sub username { $creds{username} }

my $h = sieve_get_handle("127.0.0.1:$port",
                         \&username,
                         sub { $creds{authname} },
                         sub { $creds{$_[0]} },
                         sub { '' })
    or die "login failed: " . sieve_get_global_error();
my @scripts;
sieve_list($h, sub { push @scripts, "@_" }) == 0
    or die "list failed: " . (sieve_get_error($h) // 'unknown error');
print "scripts: @scripts\n";
EOF

    $self->assert_matches(qr/^scripts: s1 1$/m, $out);
    $self->assert_str_equals('ok', $status);
}
