BEGIN { 
    $Is_Win32 = ($^O eq "MSWin32");
    if($Is_Win32) {
	require 5.004_02;
    }
    else {
	require 5.003; 
    } 
}

use ExtUtils::MakeMaker;
use Config;
use FileHandle ();
use File::Basename qw(dirname);
use File::Path qw(mkpath rmtree);
use Cwd;
use File::Copy qw(cp);

my %vcache = (); #SERVER_VERSION
my %mcache = (); #MODULE_MAGIC_NUMBER

#version 1.5 that ships with 5.003 is broken!
*cp = sub { 
    system "cp @_";
    for (@_) { -e $_ or die $! }
} if $File::Copy::VERSION < 2.0;

$VERSION = "1.00";

use subs qw(_prompt iedit);

unless ($Is_Win32) {
    report_setup();
    readline_setup();        
}

eval 'use Apache::MyConfig' ;

$APACHE_SRC_DEFAULT = $@ ? 
    '../apache_x.x/src'  :
    $Apache::MyConfig::Setup{Apache_Src} ; 

my $PWD = cwd;
my %SSL = (
    "apache_ssl.c" => "Ben-SSL",
    "mod_ssl.h"   => "Stronghold",
);

# Patch up the Makefiles we are going to use with Apache
system $^X, "-pi~", "-e", "s!^PERL\\s*=.*!PERL=$Config{'perlpath'}!",
            <src/Makefile.tmpl*>, "src/modules/perl/Makefile";

#soes yous can try out the zamples
unless (-l "t/net/perl/eg") {
    system "$Config{lns} $PWD/eg $PWD/t/net/perl/eg";
}
unless (-e "t/docs/test.shtml") {
    cp "t/docs/test.html", "t/docs/test.shtml";
}

chmod 0644, "t/conf/mod_perl_srm.conf";

#generated by us at one time or another
my(@do_clean) = qw{
   t/docs/.htaccess 
   t/docs/hooks.txt
   src/Configuration
   lib/Apache/MyConfig.pm
   Apache/Apache.xs
};
#t/conf/httpd.conf
#t/net/config.pl

for(@do_clean) { unlink $_ }
rmtree "t/docs/stacked", 0, 0;

my(@test_pre_init) = qq(
test_pre_init:
);

# Automatic setup support
my(@adirs, %seen, %mft_map, %vers_map, $src_dir, $vers, $conf, $ans);
%vers_map = (
   '1.1.1' => "Makefile.tmpl",
   '1.1.3' => "Makefile.tmpl",
   '1.2'  => "Makefile.tmpl-1.2",
   '1.1.1Xcert-Sentry' => "Makefile.tmp-XCert",
   '1.1.1Ben-SSL' => "Makefile.tmpl-Ben-SSL",
   '1.1.3Ben-SSL' => "Makefile.tmpl-Ben-SSL",
   '1.2Ben-SSL' => "",
    NONE => "", 
);	     

$EVERYTHING = 0;
$PERL_STATIC_EXTS = "";
$Port = $PORT = 8529;
$DO_HTTPD = $ENV{DO_HTTPD} || 0;
$NO_HTTPD = $ENV{NO_HTTPD} || 0;
$PERL_TRACE = 0;
$ALL_HOOKS  = 0;
$APACHE_SRC = "";
$PERL_SECTIONS = 0;
$PERL_SSI = 0;
$ADD_VERSION = 1;
$STATIC = 1;
$DYNAMIC = 0;

#callback hooks
@callback_hooks = qw{
   PERL_HANDLER PERL_CHILD_INIT PERL_CHILD_EXIT
   PERL_TRANS PERL_AUTHEN PERL_AUTHZ 
   PERL_ACCESS PERL_TYPE PERL_FIXUP
   PERL_LOG PERL_HEADER_PARSER
   PERL_INIT PERL_CLEANUP
   PERL_STACKED_HANDLERS 
   PERL_METHOD_HANDLERS
};
$callback_alias{PERL_INIT} = "PERL_HEADER_PARSER";
$callback_alias{PERL_CLEANUP} = "PERL_LOG";
%callback_hooks = map { $_,0 } @callback_hooks;
$callback_hooks{PERL_HANDLER} = 1; #PerlHandler always on
%cant_hook = ();

while($_ = shift) {
    ($k,$v) = split /=/;
    $v = 1 unless defined $v;
    ${$k} = $v, next if defined ${$k};
    $callback_hooks{$k} = $v if exists $callback_hooks{$k};
}

$STATIC = 0 if $DYNAMIC;

for (keys %callback_alias) {
    $callback_hooks{$callback_alias{$_}}++ 
       if $callback_hooks{$_};
}

if($EVERYTHING) {
    @callback_hooks{qw(PERL_STACKED_HANDLERS PERL_METHOD_HANDLERS)} = (1) x 2;
    for(qw(ALL_HOOKS PERL_SSI PERL_SECTIONS)) {
       $$_ = 1;
    }
}


if($ALL_HOOKS) {
    for (@callback_hooks) {
	next if /Handlers?$/i;
	$callback_hooks{$_}++;
    }
}

if($Is_Win32) {
    $NO_HTTPD = 1;
    win32_setup();
} 

unless ($NO_HTTPD) {
foreach $src_dir ($APACHE_SRC, qw(../apache_1.1.1/src), <../apache_1.2*/src>,
		  <../apache*/src>, <../stronghold*/src>, "../src", "./src") 
{
    next unless -d $src_dir;
    next if $seen{$src_dir}++;
    next unless $vers = httpd_version($src_dir);
    unless(exists $vers_map{$vers}) {
	print STDERR "Apache version '$vers' unsupported\n";
	next;
    }
    $mft_map{$src_dir} = $vers_map{$vers};
    #print STDERR "$src_dir -> $vers_map{$vers}\n";
    push @adirs, $src_dir;
}

unless (@adirs) {
    print "Enter `q' to stop search\n";
    while(1) {
       print "Please tell me where I can find your apache src\n" ; 
       $src_dir = _prompt("", $APACHE_SRC_DEFAULT);
       last if $src_dir eq "q";
	if(-d $src_dir) {
	    push(@adirs, $src_dir);
	    $mft_map{$src_dir} = $vers_map{httpd_version($src_dir)};
	    last;
	}
	else {
	    print "Can't stat $src_dir\n";
	}
    }
}

}

foreach $adir (@adirs) {
    $conf = "$adir/Configuration";
    $httpd_h = "$adir/httpd.h";

    if (-e $httpd_h) {
	unless($NO_HTTPD and not $DYNAMIC) {
	    unless($DO_HTTPD) {
		$ans = _prompt("Configure mod_perl with $adir ?", "y");
		next unless $ans =~ /^y$/i;
	    }
	    $APACHE_SRC = $adir;
	    $IsBenSSL = -e "$adir/apache_ssl.c";
	    last unless(-e $conf || -e "$conf.tmpl"); #building from 'make offsite-tar' 
	}
	unless ($DO_HTTPD or $NO_HTTPD) {
	    $ans = _prompt("Shall I build httpd in $adir for you?", "y");
	    ++$NO_HTTPD unless $ans =~ /^y$/i;
	}
	last if $NO_HTTPD;

	unless ($can_dash_make{$adir}) {
	    unless (-e "$adir/Makefile.tmpl.bak") {
		print STDERR "Backing up $adir/Makefile.tmpl to $adir/Makefile.tmpl.bak\n";
		cp "$adir/Makefile.tmpl", "$adir/Makefile.tmpl.bak";
	    }
	    cp "src/$mft_map{$adir}", "$adir/Makefile.tmpl";
	    print STDERR "cp src/$mft_map{$adir} $adir/Makefile.tmpl\n";
	}

	mkpath "$adir/modules/perl";
	#ignore make's output here
	`(cd $adir/modules/perl && make clean 2> /dev/null)`;

	local(*MANI);
	open *MANI, "MANIFEST" or die "open MANIFEST $!";
	my $atopdir = dirname($adir);
	#only rm and cp files mod_perl ships with
	while(<MANI>) {
	    next unless m,^src/modules/perl/,; chomp;
	    #print "rm -f $adir/$_\n";
	    unlink "$atopdir/$_";
	    #print "cp $_ $adir/$_\n";
	    cp $_, "$atopdir/$_";
	}
	close MANI;
	unless(-e "src/Configuration" and (-M "src/Configuration" < -M $conf)) {
	    unless(-e $conf) {
		cp "$conf.tmpl", $conf;
	    }
	    cp $conf, "src/Configuration";
	    $conf = "src/Configuration";

	    conf_fixup("$adir/Makefile.tmpl", $conf);
	}
    }

    unless ($NO_HTTPD) {
	$conf = "src/Configuration";
	my $dash_make;
	$dash_make = " -make $PWD/src/$mft_map{$adir} "
	    if $can_dash_make{$adir} and $mft_map{$adir};
	#print STDERR "(cd $adir; ./Configure${dash_make} -file $PWD/$conf)\n";
	system "(cd $adir && ./Configure${dash_make} -file $PWD/$conf)";
    }

    open FH, "$APACHE_SRC/Makefile";
    while(<FH>) {
	$EXTRA_CFLAGS = $1 if /CFLAGS1\s*=\s*(.*)/;
    }
    close FH;
    print "EXTRA_CFLAGS: $EXTRA_CFLAGS\n" if $EXTRA_CFLAGS;

    last if $APACHE_SRC;
}

if($DYNAMIC) {
    for (qw(Apache Constants)) {
	cp "src/modules/perl/${_}.xs", "${_}/${_}.xs" if $DYNAMIC;
    }
}

unless ($NO_HTTPD) {
    ++$STATIC if $Config{osname} =~ /^(aix|svr4|unixware)$/i;

    my $mmn    = magic_number($APACHE_SRC);
    my $httpdv = httpd_version($APACHE_SRC,1);

    unless($httpdv >= 120) {
	$callback_hooks{PERL_HEADER_PARSER} = 0;
	$cant_hook{PERL_HEADER_PARSER} = 
	    "(need 1.2.0 or higher)";
    }

    unless($httpdv >= 130) {
	$callback_hooks{PERL_CHILD_INIT} = 0;
	$cant_hook{PERL_CHILD_INIT} = 
	    "(need 1.3a1 or higher)";
    }

    unless($mmn >= 19970728) {
	$callback_hooks{PERL_CHILD_EXIT} = 0;
	$cant_hook{PERL_CHILD_EXIT} = 
	    "(need 1.3a2-dev or higher)";
    }

    setup_for_static();

    for (@callback_hooks) {
	($k,$v) = ($_,$callback_hooks{$_});

	iedit "$APACHE_SRC/modules/perl/Makefile", "s/^$k /#$k /" if $v;
	$why = ($cant_hook{$k} || "(enable with $k=1)") unless $v;
	$k =~ s/([A-Z]+)/ucfirst(lc($1))/ge;
	$k =~ s/_//g;
	$k .= "Handler" unless $k =~ /Handlers?$/;
	print $k . '.' x (25 - length($k));
	print $v ? "enabled\n" : "disabled $why\n";
    }

    unless($httpdv >= 120) {
	$PERL_SECTIONS = $PERL_SSI = 0;
	$cant_hook{PERL_SECTIONS} = $cant_hook{PERL_SSI} = 
	    "(need 1.2.0 or higher)";
    }

    iedit "$APACHE_SRC/modules/perl/Makefile", 's/^(PERL_SECTIONS) /#$1 /'
	if $PERL_SECTIONS;

    for (qw(PERL_SECTIONS PERL_SSI)) {
	$k = $_;
	$why = ($cant_hook{$_} || "(enable with $k=1)") unless $$_;
	$k =~ s/([A-Z]+)/ucfirst(lc($1))/ge;
	$k =~ s/_//g;
	$k =~ s/Ssi$/SSI/; #*shrug*
	print $k . '.' x (25 - length($k));
	print $$_ ? "enabled\n" : "disabled $why\n";
    }

    iedit "$APACHE_SRC/modules/perl/Makefile", "s/^#TRACE/TRACE/" if $PERL_TRACE;

    my $ssl_name = is_ssl();
    if($ssl_name) {
	print "I see you are building with $ssl_name,\nI'll set the SSL flags in mod_perl's Makefile\n";
	print "Before running `make test', you must add your `StrongholdKey' to t/conf/httpd.conf\n" if 
	    $ssl_name =~ /stronghold/i;
	iedit "$APACHE_SRC/modules/perl/Makefile",	"s/^#APACHE_SSL/APACHE_SSL/";
    }

    my $p54 = "-DHAVE_PERL_5__4" if $] > 5.00398;
    my $edit_note = quotemeta(<<EOF);

#---------------------------------------------------------------------
# This Makefile is derived from:
# $PWD/src/modules/perl/Makefile 
# which comes with the mod_perl distribution and 
# written by mod_perl's Makefile.PL.
# Rerunning Makefile.PL overwrites this file. Consequently...

# DO NOT EDIT THIS FILES, EDIT
#    $PWD/src/modules/perl/Makefile
# INSTEAD
#---------------------------------------------------------------------

#let's not bother with patchlevel.h
PERL_VERSION = $p54

EOF
    iedit "$APACHE_SRC/modules/perl/Makefile", "s/^#__ORIGINAL__/$edit_note/";

    if($callback_hooks{PERL_TRANS}) {
	push @test_pre_init, 
	"\t", '$(CP) t/conf/mod_perl_srm.conf /tmp', "\n";
    }
    unless (-l "t/httpd") {
	system "$Config{lns} $APACHE_SRC/httpd t/httpd";
    }
    write_extra_tests();
}

unless (-e "t/net/config.pl") {
    cp "t/net/config.pl.dist", "t/net/config.pl";
}

unless($Is_Win32 or -e "t/conf/httpd.conf") {
    cp "t/conf/httpd.conf-dist", "t/conf/httpd.conf";
    chmod 0644, "t/conf/httpd.conf";

    $User  = $Is_Win32 ? "nobody" : (getpwuid($>) || $>);
    $Group = $Is_Win32 ? "nogroup" : (getgrgid($)) || $)); 
    if($User eq "root") {
	my $other = (getpwnam('nobody'))[0];
	$User = $other if $other;
    } 
    if($User eq "root") {
	print "Cannot run tests as User `$User'\n";
        $User = _prompt("Which User?", "nobody");
	$Group = _prompt("Which Group?", $Group); 
    }
    print STDERR "Will run tests as User: '$User' Group: '$Group'\n";

    if($Port != $PORT) {
	iedit "t/conf/httpd.conf", "s/^(Port) .*/\$1 $PORT/";
	iedit "t/net/config.pl", "s/$Port/$PORT/;";
    }

    #expand ./t to full path
    iedit "t/conf/httpd.conf", "s: \./t(\S*): $PWD/t\$1:";

    for (qw(User Group)) {
	iedit "t/conf/httpd.conf", "s/^$_ .*/$_ $$_/"; 
    }
    conf_append("SSLDisable") if $IsBenSSL;
 
    #phooey!
    my $v = httpd_version($APACHE_SRC, 1);

    conf_append("LockFile /tmp/mod_perl.lock") if $v >= 121;
}


# writing Configuration to Apache::MyConfig

open FH, '>lib/Apache/MyConfig.pm'  ||
    die "Can't open lib/Apache/MyConfig.pm: $!";
print FH <<EOT;
#
# Configuartion for mod_perl and Apache::...
#
package Apache::MyConfig ;

%Setup = (
   'Apache_Src' => \'$APACHE_SRC\'
);

1;

__END__
EOT
close FH;

#checking for LWP code, borrowed from LWP's own Makefile.PL :-)
unless ($Is_Win32) {
    print "Checking for LWP::UserAgent...";
    eval {
	require LWP::UserAgent;
    };
    if ($@) {
	$no_lwp++;
	$missing_modules++;
	print "failed\n";
	print <<EOT;
$@
The libwww-perl library is needed to run the test suite.
Installation of this library is recommended, but not required.   

EOT
    sleep(2);  # Don't hurry too much
    } else {
	print "ok\n";
    }
}

eval { require CGI; };
if (not $@) {
    print "Checking CGI.pm VERSION.......";
    if($CGI::VERSION >= 2.35) {
	print "ok\n";
    }
    else {
	print "not ok\n";
	print "you need to upgrade CGI.pm from $CGI::VERSION to 2.35 or higher\n";
	sleep(10);
    }
}

if($] < 5.003_01) {
    eval { require ExtUtils::Embed };
    die "ExtUtils::Embed not installed, cannot build mod_perl\nRead the PREREQUSITES section in INSTALL document!\nStop.\n" if $@;
}

print <<EOT if $missing_modules;
The missing modules can be obtained from CPAN.  Visit
<URL:http://www.perl.com/CPAN/> to find a CPAN site near you.

EOT


sub is_ssl {
    my $d = shift || $APACHE_SRC;
    for (keys %SSL) {
	#warn "looking for $APACHE_SRC/$_\n";
	return $SSL{$_} if -e "$d/$_";
    }
    return 0;
}
  
sub write_extra_tests {
    #ensure we can find blib/ 
    local *FH;
    open FH, ">t/docs/blib.pl";
    print FH "use lib qw(\n", 
    (map { "$PWD/$_\n" } qw(blib/lib blib/arch)),
    ");\n1;\n";
    close FH;

    return unless 
	$callback_hooks{PERL_STACKED_HANDLERS} 
    and $callback_hooks{PERL_FIXUP};
    local *FH;
    my $meth_test;
    if($callback_hooks{PERL_METHOD_HANDLERS}) {
	$meth_test = <<'EOF';
#see startup.pl
PerlFixupHandler MyClass->method 
PerlFixupHandler MyClass 
PerlFixupHandler LoadClass
PerlFixupHandler LoadClass->method
EOF
    }
    my $dir = "t/docs/stacked";
    mkdir $dir, 0755;
    cp "t/docs/test.html", $dir;
    open FH, ">$dir/.htaccess";
    print FH <<EOF;
    $meth_test
PerlFixupHandler  OK DECLINED MyClass::method
EOF
        close FH;
}

WriteMakefile(
    NAME    => "mod_perl",
    VERSION => $VERSION,
    #should override `CCFLAGS', can't with older perls
    #CCDLFLAGS => "$Config{ccdlflags} $EXTRA_CFLAGS", 
    DEFINE => $EXTRA_CFLAGS, 
    macro   => {
        APACHE_SRC => $APACHE_SRC,
	ARCHNAME => $Config{archname},
	PERL_VERSION => $]+0,
	HTTPD => (is_ssl() ? "httpsd" : "httpd"),
	PORT => $PORT,
	PWD => $PWD,
    },
    'dist'    => {
	COMPRESS=> 'gzip -9f', SUFFIX=>'gz',
	CI => qq(ci -u -m\\"See Changes file\\"),
    },
    clean   => {
	FILES	=> "@do_clean",
    }
);

print "*** BSDI users: be sure to read the INSTALL `Notes' section ***\n"
    if $Config{osname} =~ /bsdos/i;

cleanup_for_static();

sub MY::clean {
    my $self = shift;
    my $string = $self->MM::clean;
    return $string if $NO_HTTPD;
    return $string unless $APACHE_SRC and -e "$APACHE_SRC/http_main.c";
    $string .= "\t-cd \$(APACHE_SRC) && \$(MAKE) clean\n";
    $string;
}

sub MY::top_targets {
    my $self = shift;
    my $string = $self->MM::top_targets;
    return $string unless $APACHE_SRC and -f "$APACHE_SRC/Configuration";
    if(-e "$APACHE_SRC/http_main.c" and !$NO_HTTPD) {
        $string =~ s/(pure_all\s+::\s+)(.*)/$1 apache_httpd $2/;
    }
    $string .= <<'EOF';

apache_httpd: $(APACHE_SRC)/Configuration	
	(cd $(APACHE_SRC) && $(MAKE) CC="$(CC)";)

tar_Apache:
	(cd $(INSTALLSITELIB); \
	     $(TAR) -cf $(PWD)/Apache.tar Apache.pm Apache/ $(ARCHNAME)/auto/Apache; )

offsite-tar:
	$(CP) MANIFEST MANIFEST.orig
	$(PERL) -e 'for (<$(APACHE_SRC)/*.h>) {' \
	-e 'system "$(CP) $$_ src/";' \
	-e 's,^$(APACHE_SRC),,;' \
	-e 'system "echo src$$_ >> MANIFEST";' \
	-e '}' 
	$(MAKE) dist
	$(RM_F) src/*.h
	$(MV) MANIFEST.orig MANIFEST

EOF

    $string;
}

sub MY::pasthru {
    return unless $APACHE_SRC;
    my $self = shift;
    chomp(my $str = $self->MM::pasthru);
    join $/, "$str\\", 
    "\t".'APACHE_SRC="$(APACHE_SRC)"\\', 
    "\t".'DEFINE="$(DEFINE)"', 
    "";   
}

sub MY::test {
    join '', @test_pre_init,
    q(
TEST_VERBOSE=0

kill_httpd:
	kill `cat /tmp/mod_perl_httpd.pid`
	@$(RM_F) /tmp/mod_perl_srm.conf
	$(RM_F) /tmp/mod_perl_httpd.pid
	$(RM_F) /tmp/mod_perl_error_log

start_httpd: test_pre_init
	@(cd t/conf; test -f httpd.conf || cp httpd.conf-dist httpd.conf)
	@(cd t/net; test -f config.pl || cp config.pl.dist config.pl)
	@$(TOUCH) /tmp/mod_perl_srm.conf
	$(APACHE_SRC)/$(HTTPD) -X -d `pwd`/t & 
	@echo httpd listening on port $(PORT)
	@echo will write error_log to: /tmp/mod_perl_error_log
	@echo "letting apache warm up...\c"
	@sleep 2
	@echo done

run_tests:
	$(FULLPERL) t/TEST $(TEST_VERBOSE)

test:	pure_all start_httpd run_tests kill_httpd

test_report:
	$(MAKE) test | t/report
);
}

sub fold_dots {
    my $v = shift;
    $v =~ s/\.//g;
    $v .= "0" if length $v < 3;
    $v;
}

sub vcache {
    my($v,$dir) = @_;
    $vcache{$dir} = fold_dots($v);
}

sub httpd_version {
    my($dir, $vnumber) = @_;
    if($vnumber) {
	return $vcache{$dir} if $vcache{$dir};
    }
    my $fh = FileHandle->new("$dir/httpd.h") or return;
    my($server, $version, $rest);
    my($fserver, $fversion, $frest);
    my($string, $extra, @vers);
    while(<$fh>) {
	next unless s/^#define\s+SERVER_(BASE|)VERSION\s+"(.*)\s*".*/$2/;
	chomp($string = $_);

	#print STDERR "Examining SERVER_VERSION '$string'...";
	#could be something like:
	#Stronghold-1.4b1-dev Ben-SSL/1.3 Apache/1.1.1 
	@vers = split /\s+/, $string;
	foreach (@vers) {
	    next unless ($fserver,$fversion,$frest) =  
		m,^([^/]+)/(\d\.\d+\.?\d*)([^ ]*),i;
	    #print STDERR "match ($fserver,$fversion,$frest)\n";  
	    if($fserver =~ /Xcert-Sentry/i or $fserver eq "Ben-SSL") {
		$extra ||= $fserver;
		#print STDERR "I see $fserver/$fversion, ok\n";
		next;
	    }

	    if($fserver eq "Apache") {
		($server, $version) = ($fserver, $fversion);
		if($version == 1.2 and $frest =~ s/^b(\d+).*/$1/) {
		    if($frest >= 8 and is_ssl($dir)) {
			$do_link_swap++;
			$can_dash_make{$dir}++;

			return $vnumber ? vcache($version,$dir) : "NONE";
		    }
		    warn "Apache/1.2b$frest is not supported, upgrade to 1.2.0.\n";
		    return undef;
		}
		elsif($version >= 1.2) {
		    $do_link_swap++ if is_ssl($dir);
		    $can_dash_make{$dir}++;
		    return $vnumber ? vcache($version,$dir) : "NONE";
		}
	    }
	    else {
		#print STDERR "'$fserver/$fversion' unrecognized.\n";
		next;
	    }
	    print STDERR "Found $fserver '$fversion' in $dir/httpd.h\n";
	}
    }
    $fh->close;
    #print STDERR "return $version$extra\n";
    return($version.$extra);
}

sub magic_number {
    my $d = shift;
    return $mcache{$d} if $mcache{$d};
    my $fh = FileHandle->new("$d/http_config.h") or die $!;
    my $n;
    while(<$fh>) {
	if(s/^#define\s+MODULE_MAGIC_NUMBER\s+(\d+).*/$1/) {
	   chomp($n = $_);
	   last;
       }
    }
    $fh->close;
    return($mcache{$d} = $n);
}

sub cleanup_for_static {
    return unless $STATIC;
    for (qw(Apache Constants)) {
	rename "${_}/${_}.xs.disabled", "${_}/${_}.xs";
    }
}

sub setup_for_static {
    my $d = "$APACHE_SRC/modules/perl";
    my $mf = "$APACHE_SRC/modules/perl/Makefile";

    iedit $mf, "s/(PERL_STATIC_EXTS) =.*/\$1 = $PERL_STATIC_EXTS/"
	if $PERL_STATIC_EXTS;

    return unless $STATIC;

    cp "Apache/typemap", $d;

    for (qw(Apache Constants)) {
	rename "${_}/${_}.xs", "${_}/${_}.xs.disabled" if -e "${_}/${_}.xs";
    }

    iedit $mf, "s/^#STATIC_/STATIC_/";
}

sub readline_setup {
    eval 'use Term::ReadLine' ;

    if ($@ eq '') {
	$::term = new Term::ReadLine 'mod_perl install';
	
	eval {
	    sub main::_prompt {
		my ($prompt, $default) = @_ ;
		
		$_ = $::term -> readline ("$prompt [$default] ") ;
		if (!/^\s*$/) {
		    s/\s+$//;
		    return $_ ;
		}
		else {
		    if ($_ eq "") {
			return $default ;
		    }
		    else {
			return "" ; 
		    }
		}
	    }
        };
	die $@ if $@;
	print "ReadLine support enabled\n" ;
    }
    else { 
	eval <<'EOT' ;
    
	sub main::_prompt {
	    prompt(@_);
	}
EOT
    }
}

sub conf_append {
    local *CFG;
    open CFG, ">>t/conf/httpd.conf" or die "open httpd.conf $!";
    print CFG join "\n", @_, "";
    close CFG;
}

sub conf_fixup {
    my($mf, $cfg) = @_;

    my $inc;
    $inc = qq{-DSERVER_SUBVERSION=\\"mod_perl/$VERSION\\" } if $ADD_VERSION;
    $inc .= " `$^X -MExtUtils::Embed -e ccopts` -I. -DUSE_PERL_SSI" if $PERL_SSI; 
    $inc .= " -DAPACHE_SSL" if is_ssl() and $PERL_SSI;
    iedit $cfg,
    q{next unless /EXTRA_CFLAGS\s*=/;}.
	q{next if /mod_perl/; chomp; }.
	    qq{\$_ .= q| $inc\n|;};

    my $ldopts = "`$^X $PWD/src/modules/perl/ldopts $PERL_STATIC_EXTS`";
    iedit $cfg,
    q{next unless /EXTRA_LIBS\s*=/;}.
    q{next if /perl/; chomp;}.
    qq{\$_ .= q| $ldopts\n|;};

    if(is_ssl() =~ /stronghold/i) {
	if($do_link_swap) {
	    warn "swapping link order in $mf for Stronghold\n";
	    my $repl = quotemeta('$(REGLIB) $(LIBS)');
	    iedit $mf, "s:\Q\$(LIBS) \$(REGLIB)\E:$repl:;";
	}
	my $repl = q{AUX_CFLAGS='\$(CFLAGS)'};
	iedit $mf, qq{s/AUX_CFLAGS="..CFLAGS."/$repl/};
    }
    {
	my $repl = q{CC='\$(CC)'};
	iedit $mf, qq{s/CC=..CC. /$repl /};
    }
    open(CONF, $cfg) || die "Can't open $cfg: $!";
    while (<CONF>) {
	$seen_modperl++ if /^Module\s+perl_module/i;
    }
    close(CONF);
    unless ($seen_modperl) {
	print "Appending mod_perl to $conf\n";
	open(CONF, ">>$cfg") || die "Can't open $cfg: $!";
	print CONF <<EOT;
		
# Embed a perl interpreter
Module perl_module         modules/perl/libmodperl.a


EOT
    close(CONF);
    } else {
	print "mod_perl already present in $conf\n";
    }
}


sub has_module {
    my($cfg, $name) = @_;
    local(*IN);
    open IN, $cfg or die "Can't open $cfg $!\n";
    while(<IN>) {
	if(/^Module\s+${name}_module/i) {
 	    close IN;
#	    print STDERR "has module_$name\n";
	    return 1;
	}
    }
    return 0;
}
 
sub report_setup {
    local(*IN,*OUT);
    open IN, "t/report.PL" or die;
    open OUT, ">t/report" or die;
    print OUT "#!$Config{perlpath}\n", join '', <IN>;
    close OUT;
    close IN;
    chmod 0755, "t/report";
}

sub iedit {
    my $file = shift;
    #print STDERR "-e @_\n";
    system $^X, "-pi~", "-e", "@_", $file;
}

sub win32_setup {
    my $d = "src/modules/perl";
    dirent_kludge($d);
    cp "Apache/typemap", $d;
    chdir $d;
    system "$^X -MExtUtils::Embed -e xsinit -- -std Apache Apache::Constants $PERL_STATIC_EXTS";
    my $lib = $Config{privlibexp};
    for (qw(Constants Apache)) {    
        system "$^X $lib/ExtUtils/xsubpp -typemap $lib/ExtUtils/typemap $_.xs > $_.c";

    }
    chdir "../../../";
}

sub dirent_kludge {
    my $d = shift;
    local *FH;
    open FH, ">$d/dirent.h" or die "can't write $d/dirent.h $!";
    print FH <<EOF;
/* major kludge to workaround confilct(s) between perl's dirent.h apache's readdir.h */

#ifdef WIN32

#define _INC_DIRENT
#define DIR void

#endif

EOF
    close FH;
}
