# -*- perl -*-

require 5.004;
use strict;
require Config;
require File::Basename;
require File::Path;

my($EXPERIMENTAL) = 1;


use vars qw($MyConfig);

if (!$MyConfig) {
    my $file;
    foreach $file (".status", "../.status") {
	if (-f $file) {
	    $@ = '';
	    $MyConfig = do $file;
	    if ($@) {
		die "Error while loading $file: $@";
	    }
	    last;
	}
    }
    if (!$MyConfig) {
	die "No such file: .status";
    }
}


sub Extract ($$$$$$) {
    my($from, $to, $driver, $dbd_driver, $version, $dbd_version) = @_;
    my($on) = 1;
	
    my $dir = File::Basename::dirname($to);
    if (!(-d $dir)  &&  !File::Path::mkpath([$dir], 0, 0755)) {
	die "Cannot create directory $dir: $!";
    }

    if (!open(IN, "<$from")) {
	print STDERR "Cannot open $from for reading: $!\n";
	exit 10;
    }
    my ($line, $contents);
    $contents = '';
    while (defined($line = <IN>)) {
	if ($line =~ /^\#xtract\s+(\S+)\s*$/) {
	    $on = ($1 eq $driver)
		||  ($1 eq 'experimental'  &&  $EXPERIMENTAL);
	} elsif ($line =~ /^\#endxtract\s*/) {
	    $on = 1;
	} elsif ($on) {
	    $contents .= $line;
	}
    }
    close IN;

    $contents =~ s/\~startperl\~/$Config::Config{startperl}/;
    $contents =~ s/\~DRIVER\~/$driver/g;
    $contents =~ s/\~DBD_DRIVER\~/$dbd_driver/g;
    $contents =~ s/\~NODBD_VERSION\~/$version/g;
    $contents =~ s/\~DBD_VERSION\~/$dbd_version/g;
    $contents =~ s/\~(\w+)\~/$MyConfig->{$dbd_driver}->{$1}/eg;

    if (-f $to  &&  open(OUT, "<$to")) {
	my($oContents) = '';
	while (defined($line = <OUT>)) {
	    $oContents .= $line;
	}
	close(OUT);
	if ($oContents eq $contents) {
	    return;
	}
    }
	
    if (!open(OUT, ">$to")) {
	print STDERR "Cannot open $to for writing: $!\n";
	exit 10;
    }
    
    if (!print OUT $contents  ||  !close OUT) {
	print STDERR "Cannot write $to: $!\n";
	exit 10;
    }
}

if (!$ENV{'XTRACT_NOT_RUNNING'}) {
    if (@ARGV != 6) {
	print "Usage: $0 <from> <to> <driver> <dbd_driver> <version>",
	    " <dbd_version>\n";
	exit 10;
    }

    Extract($ARGV[0], $ARGV[1], $ARGV[2], $ARGV[3], $ARGV[4], $ARGV[5]);
}

1;
