use strict;
use warnings;

use RT::Test::Crypt GnuPG => 1, tests => undef;
use Test::Warn;

{
    my $mail = <<EOF;
From: root\@localhost
Subject: a ticket
X-RT-Incoming-Encryption: Success
X-RT-Incoming-Signature: Success

This was _totally_ encrypted.
EOF

    my ($status, $id) = RT::Test->send_via_mailgate($mail);
    ok $id, "created a ticket";

    my $ticket = RT::Ticket->new( RT->SystemUser );
    $ticket->Load( $id );
    ok $ticket->id, "loaded ticket";

    my $txn = $ticket->Transactions->First;
    my ($msg, $attach, $orig) = @{$txn->Attachments->ItemsArrayRef};

    like( $msg->Content, qr/This was _totally_ encrypted/, "Found the right attachment" );

    is( $msg->GetHeader('X-RT-Incoming-Encryption'),
        'Not encrypted',
        'Incoming encryption header is removed'
    );

    is( $msg->GetHeader('X-RT-Incoming-Signature'),
        undef,
        'Incoming signature header is removed'
    );
}



{
    my $mail = <<EOF;
From: root\@localhost
Subject: a ticket
X-RT-Incoming-Encryption: Success
X-RT-Incoming-Signature: Success

-----BEGIN PGP MESSAGE-----
Version: GnuPG v1.4.11 (GNU/Linux)

This was _totally_ encrypted.
-----END PGP MESSAGE-----
EOF

    my ($status, $id);
    {
        my @warnings;
        local $SIG{__WARN__} = sub { push @warnings, @_ };
        ($status, $id) = RT::Test->send_via_mailgate($mail);
        ok $id, "created a ticket";

        like($warnings[0], qr/(?:keyring|keybox) .* created/, 'GnuPG warning');
        like($warnings[1], qr/Failure during GnuPG data: No data has been found\. The reason is 'Invalid packet found'/, 'GnuPG warning');
        like($warnings[2], qr/Failure during GnuPG data: No data has been found\. The reason is 'No armored data'/, 'GnuPG warning');

        # GnuPG 2.4.5+ issues another warning for gpg-exit
        if ( $warnings[3] ) {
            like($warnings[3], qr/Failure during GnuPG gpg-exit: Failed to gpg-exit/, 'GnuPG warning');
        }
    }

    my $ticket = RT::Ticket->new( RT->SystemUser );
    $ticket->Load( $id );
    ok $ticket->id, "loaded ticket";

    my $txn = $ticket->Transactions->First;
    my ($msg, $attach, $orig) = @{$txn->Attachments->ItemsArrayRef};

    like( $msg->Content, qr/This was _totally_ encrypted/, "Found the right attachment" );

    is( $msg->GetHeader('X-RT-Incoming-Encryption'),
        undef,
        'Incoming encryption header is removed'
    );

    is( $msg->GetHeader('X-RT-Incoming-Signature'),
        undef,
        'Incoming signature header is removed'
    );
}

done_testing;
