%# If ignorance is bliss, why aren't there more happy people?
<%INIT>

require RT::CompanySpecific if $RT::CompanySpecific;

if ($r->uri eq '/Work/Approvals/Count.html') {
    $m->comp('/Work/Approvals/Count.html', %ARGS);
    $m->abort;
}

# hack only!
if ($RT::XXXHack and $user and $ARGS{pass} eq 'hack') {
    $session{'CurrentUser'} ||= RT::CurrentUser->new;
    $session{'CurrentUser'}->Load( $user );
    return;
}

return unless $RT::OIN104;

if ($ARGS{user} eq 'root') {
    $RT::AllowRemoteRootLogin or eval {
        require Apache::Connection;
        $r->connection->remote_ip =~ /^(?:127\.0\.0\.1|::1)$/
    } or Abort(loc("Remote root login is disallowed."));
}

require Digest::MD5;
require URI::Escape;
return unless defined($check);

my $secret = 'some secret string here';
my $secfile = 'Secret.asp';

# Reading the seckey from HKEY_LOCAL_MACHINE\SOFTWARE\104 eHR\eReportRoot
require Win32::TieRegistry;
my $dir = $Win32::TieRegistry::Registry->{"HKEY_LOCAL_MACHINE\\Software\\104 eHR\\"}{''};
$dir =~ s/\\$//;
$secfile = "$dir\\eWorkflow\\$secfile";

if (open(my ($fh), $secfile)) {
    while (<$fh>) {
	next unless /strSecret\s*=\s*"([^"]*)"/;
	$secret = $1; last;
    }
    close $fh;
}

$cname = Encode::encode(big5 => $cname);
my $k = URI::Escape::uri_escape("$odbcname $id $cname $now $secret", "^a-zA-Z\\d");
$k =~ s/%20/+/g; # special case, heh.
my $my_check = Digest::MD5::md5_hex($k);
# return unless ($my_check eq $check); #XXX

# check that $now is sufficiently recent, to prevent URL abuse
$now =~ s/\QW\E(.*)/$1AM/;
$now =~ s/\QU\E(.*)/$1PM/;

$now =~ s/%3A/:/g;
$now =~ s/%2F/-/g;
$now =~ s/%A4%C8/M/g;
$now =~ s/%A4U/P/g;
$now =~ s/%A4W/A/g;
$now =~ s/\\x3A/:/g;
$now =~ s/\\x2F/-/g;
$now =~ s/\\xA4\\xC8/M/g;
$now =~ s/\\xA4U/P/g;
$now =~ s/\\xA4W/A/g;
$now =~ s/\+/ /g;
$now =~ s/(.M) (..:..:..)$/$2/;
if ($1 eq 'PM') {
    $now =~ s/(..)(:..:..)$/($1 + 12) . $2/e;
}

# XXX - why does this not work? must investigate!
require Date::Parse;
my $time = Date::Parse::str2time($now);
#return unless (time - $time < 120); #XXX

#$m->print("$time from $now is " . time());
#$m->abort;
#$m->comp('Default');
$session{'CurrentUser'} = RT::CurrentUser->new($RT::SystemUser);
#iunless $session{CurrentUser} and $session{CurrentUser}->Id;
#$m->print($id);
if ($id > 0) {
    $session{'CurrentUser'}->LoadByCol( ExternalAuthId => $id );
} else {
    $session{'CurrentUser'}->Load( 'root' );
}

$session{'PortalURL'} = $portalurl;

if (my $obj = $session{'CurrentUser'}->UserObj) {
    return unless $obj->Disabled;
    $obj->SetDisabled(0);
}
#$m->print("comparing " . $session{CurrentUser}->UserObj->Name);
#$m->print("CurrentUser: $session{'CurrentUser'}");
#$m->print("ID: ",eval{$session{'CurrentUser'}->Id});
#$m->comp('/Elements/SetupSessionCookie', %ARGS);
#$m->abort;

</%INIT>
<%ARGS>
$odbcname	=> undef
$portalurl	=> undef
$id		=> undef
$cname		=> undef
$now		=> undef
$check		=> undef
$user		=> undef
</%ARGS>
