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

sub test_managesieve_referral_chain
    ($self)
{
    my $auth = sub ($authzid, $authcid, $password) {
        "$authzid/$authcid/$password" eq 'user/auth/secret'
            ? "OK\r\n" : qq{NO "bad credentials"\r\n};
    };
    my $refer = sub ($srv, $authinfo, $role) {
        my $port = $srv->port($role);
        qq{BYE (REFERRAL "sieve://${authinfo}127.0.0.1:$port") "moved"\r\n};
    };

    # The second referral has no credentials of its own, so reuses the
    # ones the first referral supplied.
    my $srv = Cassandane::Net::FakeManageSieve->new(
        start => {
            LISTSCRIPTS => sub ($srv, @) { $refer->($srv, 'auth;user@', 'middle') },
        },
        middle => {
            auth => $auth,
            LISTSCRIPTS => sub ($srv, @) { $refer->($srv, '', 'end') },
        },
        end => {
            auth => $auth,
            LISTSCRIPTS => sub { qq{"s1" ACTIVE\r\nOK\r\n} },
        },
    );

    # Make glibc scribble over freed memory, so reading it shows.
    local $ENV{MALLOC_PERTURB_} = 165;
    my ($status, $out) = $srv->run_client($self->{instance}, <<'EOF', $srv->port('start'));
my ($port) = @ARGV;
sub cb { $_[0] eq 'password' ? 'secret' : 'nobody' }

my $h = sieve_get_handle("127.0.0.1:$port", "cb", "cb", "cb", "cb")
    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);
}
