# -*- perl -*-

use strict;
require ExtUtils::MakeMaker;
require Config;
require DBI::DBD;
use lib "../lib";

require DBD::~~dbd_driver~~::Install::Config;

use vars qw($cfg);
$cfg = $DBD::~~dbd_driver~~::Install::Config::configuration;
if (!$cfg) {
    die "Missing driver configuration";
}

my @pl_files = (%{$cfg->{'files'}});
if ($cfg->{'install_nodbd'}) {
    push(@pl_files, (%{$cfg->{'files_nodbd'}}));
}


my %hash = %{$cfg->{'makemaker'}};
$hash{'NAME'} = 'DBD::' . $cfg->{'dbd_driver'};
$hash{'PL_FILES'} = { @pl_files };
$hash{'OBJECT'} = '$(O_FILES)';
$hash{'VERSION'} = $cfg->{'dbd_version'};
$hash{'clean'} = { 'FILES' => '*.xsi' };
ExtUtils::MakeMaker::WriteMakefile(%hash);


package MY;

sub libscan {
    my($self, $path) = @_;
    ($path =~ /(Install\.pm|,v|~)$/) ? undef : $path;
}

sub processPL {
    my($self) = shift;
    my @output;
    my $cfg = "../lib/DBD/~~dbd_driver~~/Install/Config.pm";
    my($from, $to);
    while (($from, $to) = each %{$self->{'PL_FILES'}}) {
	$from = "../$from";
	if ($to =~ /^~~dbd_driver~~\//) {
	    $to =~ s/^~~dbd_driver~~\///;
	} else {
	    $to = "../$to";
	}
	push(@output, <<"PART");
pm_to_blib: $to

$to: $from
	\$(PERL) -I\$(INST_ARCHLIB) -I\$(INST_LIB) -I\$(PERL_ARCHLIB) \\
		-I\$(PERL_LIB) -I../lib -MExtUtils::PerlPP \\
		-e "ppp('$from', '$to', '$cfg')"

PART
    }
    join "", @output;
}


sub postamble {
    my $self = shift;

    my $pa = "\n";

    my ($dir, $dbiDir);
    foreach $dir ($self->{INSTALLSITEARCH}, @INC) {
	if (-f "$dir/auto/DBI/Driver.xst") {
	    $dbiDir = $dir;
	    last;
	}
    }
    if (!$dbiDir) {
	die "Unable to detect location of 'Driver.xst'.\n";
    }

    $pa .= '
DBI_DRIVER_XST_DIR=' . $dbiDir . '/auto/DBI
DBI_DRIVER_XST=$(DBI_DRIVER_XST_DIR)/Driver.xst

$(BASEEXT).xs: $(BASEEXT).xsi

$(BASEEXT).c: $(BASEEXT).xsi

$(BASEEXT).xsi: $(DBI_DRIVER_XST)
	perl -p -e "s/\~DRIVER\~/$(BASEEXT)/g" < $(DBI_DRIVER_XST) > $(BASEEXT).xsi
';

    $pa;
}


sub const_loadlibs {
    my $self = shift;
    my $str = $self->SUPER::const_loadlibs(@_);
    if (my $el = $::cfg->{'static_libs'}) {
        $str =~ s/((?:EXTRALIBS|LDLOADLIBS)\s+=\s+)/$1$el /sg;
    }
    $str;
}