#!/usr/bin/env perl
use strict;
use warnings;

# Determine where RT is installed
if ($ENV{RTHOME}) {
    die "Invalid RTHOME $ENV{RTHOME}\n"
        unless -d $ENV{RTHOME} and -e "$ENV{RTHOME}/lib/RT.pm";
} elsif (-d "/opt/rt4" and -e "/opt/rt4/lib/RT.pm") {
    warn "Found RT in /opt/rt4\n";
    $ENV{RTHOME} = "/opt/rt4";
} elsif (-d "/opt/rt3" and -e "/opt/rt3/lib/RT.pm") {
    warn "Found RT in /opt/rt3\n";
    $ENV{RTHOME} = "/opt/rt3";
} else {
    die "Can't determine where RT is installed into; set the RTHOME environment variable\n" .
        "to the location of the base of your RT install.\n";
}

# The perl currently running is probably whatever was first in the path,
# which may not be what the installed RT uses.  Peek at the installed
# shebang lines to find out what we should re-exec ourselves with.
my $perl = find_perl();
if (not defined $perl) {
    warn "Can't determine perl binary that RT uses; assuming $^X\n";
} elsif (($ENV{PERL} || $^X) ne $perl) {
    warn "Using $perl to load RT...\n";
    $ENV{PERL} = $perl;
    exec($ENV{PERL}, $0) or die "Failed to run $perl: $!";
}


# Load RT
unshift @INC, "$ENV{RTHOME}/lib";
unshift @INC, "$ENV{RTHOME}/local/lib";

eval { require RT };
die "Failed to load RT: $@\n" if $@;

RT::LoadConfig();
RT::Init();


# Clean up the transactions
require RT::Transactions;
no warnings 'once';
my $txns = RT::Transactions->new( $RT::SystemUser );
$txns->Limit(
    FIELD => "ObjectType",
    VALUE => "RT::User",
);
$txns->Limit(
    FIELD => "Field",
    VALUE => "Password",
);
$txns->Limit(
    FIELD    => "NewValue",
    OPERATOR => "!=",
    VALUE    => "********",
);
print "Cleaning up " . $txns->Count . " transactions\n";
while (my $txn = $txns->Next) {
    $txn->__Set( Field => $_, Value => '********' )
        for qw/OldValue NewValue/;
}
print "Done.\n";


sub find_perl {
    my @files = qw|bin/rt bin/standalone_httpd sbin/standalone_httpd|;
    my ($file) = grep {-e $_} map {"$ENV{RTHOME}/$_"} @files;
    return undef unless $file;

    open(my $fh, "<", $file) or return;
    my ($shebang) = <$fh>;
    $shebang =~ /^#!(\S+)/ or return;

    return undef unless -x $1;
    return $1;
}
