#!perl
use Cassandane::Tiny;
use Digest::SHA qw(sha256);

# Content-Digest is of the message content (RFC 9530 Section 2): only the
# range of a 206, the compressed bytes of a compressed response, and, for a
# chunked response, sent as a trailer once all of it is known.
sub test_content_digest_content
    :NoStartInstances
    ($self)
{
    $self->{instance}->{config}->set(httpallowcompress => 'yes');
    $self->_start_instances();

    my $path = '/dav/calendars/user/cassandane/Default/content-digest.ics';
    my $description = join(' ', map { "line $_ of a long description." } 1..40);
    my $ical = join("\r\n",
        'BEGIN:VCALENDAR', 'VERSION:2.0', 'PRODID:-//Cassandane//EN',
        'BEGIN:VEVENT', 'UID:content-digest', 'DTSTAMP:20260101T000000Z',
        'DTSTART:20260101T100000Z', 'DURATION:PT1H',
        'SUMMARY:Content-Digest test', "DESCRIPTION:$description",
        'END:VEVENT', 'END:VCALENDAR', '');

    my $put = $self->http1_request(
        method  => 'PUT',
        path    => $path,
        headers => [ 'content-type' => 'text/calendar',
                     'connection'   => 'close' ],
        body    => $ical,
        timeout => 10,
    );
    $self->assert_str_equals('201', $put->{statuses}[0] // '');

    my sub get (@hdrs) {
        my $target = shift @hdrs;
        my $service = $self->{instance}->get_service('http');
        my $s = $self->http1_connect();
        http1_send($s,
            "GET $target HTTP/1.1\r\n",
            "Host: ", $service->host, ":", $service->port, "\r\n",
            "Authorization: Basic ", encode_base64('cassandane:pass', ''),
            "\r\n",
            "Want-Content-Digest: sha-256=10\r\n",
            (map { "$_\r\n" } @hdrs),
            "\r\n");
        my $res = http1_read_response($s);
        close($s);
        return $res;
    }

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

    xlog $self, "a range: the digest is of the bytes sent";
    my $res = get($path, 'Range: bytes=10-29');
    $self->assert_num_equals(20, length $res->{body});
    $self->assert_http_response({
        status  => 206,
        headers => { 'content-digest' => digest($res->{body}) },
    }, $res);
    $self->assert_str_not_equals(digest($ical),
                                 $res->{headers}{'content-digest'});

    xlog $self, "compressed: the digest is of the compressed bytes";
    $res = get($path, 'Accept-Encoding: gzip');
    $self->assert_http_response({
        status  => 200,
        headers => { 'content-encoding' => 'gzip',
                     'content-digest'   => digest($res->{body}) },
    }, $res);

    xlog $self, "chunked: the digest is a trailer";
    $res = get('/dav/calendars/user/cassandane/Default/');
    $self->assert_http_response({
        status   => 200,
        headers  => { 'transfer-encoding' => re(qr/^chunked$/i),
                      trailer             => re(qr/\bContent-Digest\b/),
                      'content-digest'    => undef },
        trailers => { 'content-digest' => digest($res->{body}) },
        body     => re(qr/^UID:content-digest\r$/m),
    }, $res);
}
