#!perl
use Cassandane::Tiny;
use Digest::SHA qw(sha256);
use IO::Uncompress::Gunzip qw(gunzip $GunzipError);
use MIME::Base64 qw(encode_base64);

# A chunked response's Content-Digest and Unencoded-Digest are trailers
# that follow all of its body, even when flow control holds part of the
# body back: Content-Digest of the compressed bytes sent, Unencoded-Digest
# of the representation before compression.
sub test_content_digest_trailer
    :needs_dependency_nghttp2 :NoStartInstances
    ($self)
{
    $self->config_set(httpallowcompress => 'yes',
                      httpmodules => 'caldav carddav');
    $self->_start_instances();
    $self->_setup_http_service_objects();

    my $carddav = $self->{carddav};
    for my $i (1..20) {
        my $card = "BEGIN:VCARD\r\nVERSION:3.0\r\nUID:card-$i\r\n"
                 . "FN:Person $i\r\nN:$i;Person;;;\r\n"
                 . "NOTE:" . join(' ', map { "$i.$_" } 1..60) . "\r\n"
                 . "END:VCARD\r\n";
        $carddav->Request('PUT', "Default/card-$i.vcf", $card,
                          'Content-Type' => 'text/vcard');
    }

    my sub digest ($data) {
        return 'sha-256=:' . encode_base64(sha256($data), '') . ':';
    }

    xlog $self, "GET the addressbook, compressed, with a 1 KiB window";
    my $res = $self->http2_request(
        method         => 'GET',
        path           => '/dav/addressbooks/user/cassandane/Default/',
        headers        => [ 'accept-encoding'       => 'gzip',
                            'want-content-digest'   => 'sha-256=10',
                            'want-unencoded-digest' => 'sha-256=10' ],
        initial_window => 1024,
    );
    $self->assert_num_equals(200, $res->{status});
    $self->assert(length $res->{body} > 1024);

    my $representation;
    gunzip(\$res->{body} => \$representation)
        or die "gunzip failed: $GunzipError";
    my $ncards = () = $representation =~ /^END:VCARD\r$/mg;
    $self->assert_num_equals(20, $ncards);

    $self->assert_cmp_deeply({
        'content-encoding' => 'gzip',
        trailer            => 'Unencoded-Digest, Content-Digest',
        'content-digest'   => undef,
        'unencoded-digest' => undef,
    }, { map { $_ => $res->{headers}{$_} }
         qw(content-encoding trailer content-digest unencoded-digest) });
    $self->assert_cmp_deeply({
        'content-digest'   => digest($res->{body}),
        'unencoded-digest' => digest($representation),
    }, $res->{trailers});
}
