#!perl
########################################################################
# A perl script to download and install the apxs, apr-config,
# and apu-config utiltities for Win32 for use with Apache2.
# For problems, please contact Randy Kobes <randy@theoryx5.uwinnipeg.ca>
#########################################################################
use strict;
use warnings;
require File::Spec;
use Archive::Tar;
use File::Path;
use ExtUtils::MakeMaker;
use LWP::Simple;
die 'This is intended for Win32' unless $^O =~ /Win32/i;

my $file = 'apxs_win32.tar.gz';
my @path_ext;
path_ext();

print << 'END';

This script will download and install the apxs,
apr-config, and apu-config utilities for Win32
for use with Apache2.

END

if (my $hit = which('apxs')) {
    print << "END";

An apxs program was found in $hit. Continuing
with the installation will overwrite this.

END
    my $ans = prompt('Continue?', 'no');
    exit(0) unless $ans =~ /^y/i;
}

my $remote = 'https://apache.org/dist/perl/win32-bin/' . $file;
print "Fetching $remote ... ";
unless (is_success(getstore($remote, $file))) {
    die "Download of $remote failed";
}
print " done!\n";

my $arc = Archive::Tar->new($file, 1);
$arc->extract($arc->list_files());
my $dir = 'apxs';
die "Unpacking $file failed" unless -d $dir;
print "chdir $dir\n";
chdir $dir or die "chdir to $dir failed: $!";
my @args = ($^X, 'Configure.pl');
print "@args\n\n";
system(@args) == 0
    or die "system @args failed: $?";
chdir '..';
rmtree($dir, 1, 1) or warn "rmtree of $dir failed: $!";
print "unlink $file\n";
unlink $file or warn "unlink of $file failed: $!";

sub drives {
  my @drives = ();
  eval{require Win32API::File;};
  return map {"$_:\\"} ('C' .. 'Z') if $@;
  my @r = Win32API::File::getLogicalDrives();
  return unless @r > 0;
  foreach (@r) {
    my $t = Win32API::File::GetDriveType($_);
    push @drives, $_ if ($t == 3 or $t == 4);
  }
  return @drives > 0 ? @drives : undef;
}

sub path_ext {
    if ($ENV{PATHEXT}) {
        push @path_ext, split ';', $ENV{PATHEXT};
        for my $ext (@path_ext) {
            $ext =~ s/^\.*(.+)$/$1/;
        }
    }
    else {
        #Win9X: doesn't have PATHEXT
        push @path_ext, qw(com exe bat);
    }
}

sub which {
    my $program = shift;
    return unless $program;
    my @drives = drives();
    my @extras = ();
    if (@drives > 0) {
        for my $drive (@drives) {
            for ('Apache2', 'Program Files/Apache2',
                 'Program Files/Apache Group/Apache2') {
                push @extras, File::Spec->catpath($drive, $_);
            }
        }
    }
    my @a = map {File::Spec->catfile($_, $program) }
        (File::Spec->path(), @extras);
    for my $base (@a) {
        return $base if -x $base;
        for my $ext (@path_ext) {
            return "$base.$ext" if -x "$base.$ext";
        }
    }
    return;
}