use strict;
use warnings;

use RT::Test::Crypt
  GnuPG         => 1,
  tests         => undef,
  gnupg_options => {
    passphrase    => 'rt-test',
    'trust-model' => 'always',
  };

RT::Test->import_gnupg_key('rt-recipient@example.com');
RT::Test->import_gnupg_key('general@example.com');

# Determine the key IDs of the newly-loaded keys
my %secret_keys;
{
    my %info = RT::Crypt->GetKeysInfo( Protocol => 'GnuPG', Type => 'private', Force => 1 );
    for my $key (@{$info{info}}) {
        my $user = $key->{User}[0]{String};
        $user = (Email::Address->parse( $user ))[0]->address;
        $secret_keys{$user} = $key->{Fingerprint};
    }
}

my $queue = RT::Test->load_or_create_queue(
    Name              => 'Signing',
    CorrespondAddress => 'rt-recipient@example.com',
    CommentAddress    => 'rt-recipient@example.com',
);
ok $queue && $queue->id, 'loaded or created queue';

my ( $baseurl, $m ) = RT::Test->started_ok;
ok $m->login, 'logged in';

sub create_signed {
    my $key = shift;
    diag( "Attempting to sign using $key" );

    $m->goto_create_ticket( $queue->id );
    $m->form_name('TicketCreate');
    unless ($m->current_form->find_input("SignUsing")) {
        my $content = $m->content;
        $content =~ s!using Queue(?:'|&#39;)s key!using <input type="text" name="SignUsing" />!;
        $m->update_html( $content );
    }

    $m->form_name('TicketCreate');
    $m->field( Subject    => 'test' );
    $m->field( Requestors => 'rt-test@example.com' );
    $m->field( Content    => 'Some content' );
    $m->tick( Sign => 1 );
    $m->field( SignUsing  => $key );
    $m->click('SubmitTicket');
}

create_signed( '' );
$m->content_lacks("unable to sign outgoing email messages");
my @mail = RT::Test->fetch_caught_mails;
is( scalar @mail, 1, "Got a mail" );
like( $mail[0], qr/BEGIN PGP SIGNATURE/, "Is signed" );


create_signed( 'rt-recipient@example.com' );
$m->content_lacks("unable to sign outgoing email messages");
@mail = RT::Test->fetch_caught_mails;
is( scalar @mail, 1, "Got a mail" );
like( $mail[0], qr/BEGIN PGP SIGNATURE/, "Is signed" );


create_signed( 'general@example.com' );
$m->content_contains("unable to sign outgoing email messages");
@mail = RT::Test->fetch_caught_mails;
is( scalar @mail, 0, "Sent no mail" );

create_signed( $secret_keys{'general@example.com'} );
$m->content_contains("unable to sign outgoing email messages");
@mail = RT::Test->fetch_caught_mails;
is( scalar @mail, 0, "Sent no mail" );


my $user = RT::User->new( RT->SystemUser );
$user->Load( 'root' );
my ($ok, $msg) = $user->SetPrivateKey( $secret_keys{'general@example.com'} );
ok($ok, "Set private key to $secret_keys{'general@example.com'}: $msg" );


create_signed( $secret_keys{'general@example.com'} );
$m->content_lacks("unable to sign outgoing email messages");
@mail = RT::Test->fetch_caught_mails;
is( scalar @mail, 1, "Sent a mail" );
like( $mail[0], qr/BEGIN PGP SIGNATURE/, "Is signed" );

done_testing;
