#!"%PATH%\Common\perl\bin\perl.exe"

BEGIN { $0 = __FILE__ };

use strict;
use FindBin;
use lib grep -d, map "$FindBin::Bin/../../$_", (
    "win32/lib",
    "win32/lib/".sprintf('%vd', $^V),
    "rt/lib",
    "rt/local/lib",
    "winrt/conf",
);

eval {
    if ($^O eq 'MSWin32') {
        # Add library lookup path for libexpat.dll etc.
        $ENV{PATH} = join(
	    ';',
	    (map { my $dir = $_; $dir =~ s{/}{\\}g; Win32::GetShortPathName($dir) } 
	    "$FindBin::Bin/../../../Common/perl/bin",
	    "$FindBin::Bin/../../../Common/httpd/bin"),
	    $ENV{PATH},
	);

	require Win32::TieRegistry;
	$RT::OIN104 = $Win32::TieRegistry::Registry
	    ->{'HKEY_LOCAL_MACHINE\Software\SecureScout\Request Tracker'}
	    ->{'OIN104'};
        unshift @INC, "$FindBin::Bin/../../104/lib" if $RT::OIN104;
    }
    else {
	$RT::OIN104 = (-d "$FindBin::Bin/../../104");
        unshift @INC, "$FindBin::Bin/../../104/lib" if $RT::OIN104;

	require RT;
	$RT::BasePath = "$FindBin::Bin/../../rt";
	$RT::SITE_CONFIG_FILE = "$FindBin::Bin/../conf/RT_Config.pm";
    }

    1;
} and eval {
    local $ENV{PATH};
    my $config = $RT::SITE_CONFIG_FILE ||
                 "$FindBin::Bin/../../rt/etc/RT_Config.pm";
    $config =~ s{/[\w ]+/[\w ]+/[ \w ]+/\.\./\.\.}{/Common/../Request Tracker};
    $INC{$config} = $config;

    do_require("$FindBin::Bin/../../rt/lib/RT.pm.in");
    require WinRT;

    do_require("$FindBin::Bin/../../rt/bin/webmux.pl.in")
      if $^O eq 'MSWin32';

    local *RT::Set = sub { $_[0] = $_[1] unless defined $_[0] }; 
    do_require("$config.in");

    do_require("$FindBin::Bin/../../rt/bin/webmux.pl.in")
      if $^O ne 'MSWin32';

    # XXX - Work around Test::Builder's duping of STDERR
    local $^C = 1;
    require Test::Builder;
    1;
} and eval {
    $WinRT::DB->Launch if $WinRT::DB; # make sure we have a valid DB connection
    $WinRT::RELAY->Launch if $WinRT::RELAY; # make sure we have a valid email relay
    require Apache2;
    require Apache::DBI;
    1;
} or do {
    open ERR, ">>$FindBin::Bin/../../logs/modperl2.log" or warn $!;
    print ERR __FILE__ . " startup error: $@\n\n";
    close ERR;
    warn $@;
    # ... proceed as normal! ...
};

sub do_require {
    if ($^O ne 'MSWin32') {
        delete $INC{substr($_[0], 0, -3)};
        require substr($_[0], 0, -3);
        return;
    }
    my $file = shift;
    open my $fh, $file or die $!;
    my $webmux = do { local $/; <$fh> };
    close $fh;
    $webmux =~ s/\@\w+\@//g;
    no strict;
    eval $webmux;
    die $@ if $@;
    $INC{$1} = $file if $file =~ m{([^/]+)\.in$};
}

1;
