use strict;
use warnings;

use RT::Test tests => undef;

RT->Config->Set( MailCommand  => 'sendmailpipe' );
RT->Config->Set( VERPPrefix   => "verp-" );
RT->Config->Set( VERPDomain   => "example.com" );

# Ensure that the fake sendmail knows where to write to
$ENV{RT_MAILLOGFILE} = RT::Test->temp_directory . "/sendmailpipe.log";
my $fake = File::Spec->rel2abs( File::Spec->catfile(
        't', 'security', 'fake-sendmail' ) );
RT->Config->Set( SendmailPath => $fake);

ok(
    RT::Test->set_rights(
        { Principal => 'Everyone',  Right => [qw/CreateTicket/] },
    ),
    'set rights'
);

my $bad = RT::Test->load_or_create_user(
    EmailAddress => 'danger-$USER@example.com',
);
ok( $bad, "Got a user object back" );
ok( $bad->id, "Successfully created a user" );

my $current_user = RT::CurrentUser->new(RT->SystemUser);
my ($id, $msg) = $current_user->Load($bad->Id);
ok( $id, "Loaded the user successfully" );

my $ticket = RT::Ticket->new( $current_user );
($id, $msg) = $ticket->Create(
    Requestor => $bad->Id,
    Subject   => "Danger, Will Robinson!",
    Queue     => "General"
);
ok( $id, "Created a ticket: $msg" );

open(LOG, "<", $ENV{RT_MAILLOGFILE}) or die "Can't open log file: $!";
while (my $line = <LOG>) {
    next unless $line =~ /^-f/;
    like($line, qr/\$USER/, "Contains uninterpolated \$USER");
}
close(LOG);

done_testing;
