use strict;
use warnings;

use RT::Test::GnuPG 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);
    warnings_like {
        ($status, $id) = RT::Test->send_via_mailgate($mail);
        ok $id, "created a ticket";
    } [qr/keyring .* created/,
       qr/Failure during GnuPG data: No data has been found\. The reason is 'Invalid packet found'/,
       qr/Failure during GnuPG data: No data has been found\. The reason is 'No armored data'/,
   ];

    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;
