#!/usr/bin/perl
use File::Find;
use Cwd qw(abs_path getcwd);
use File::Path qw(make_path remove_tree);
use POSIX qw(strftime);
use File::Copy;

die "expected 'scripts/xml-casa' executable to exist" unless -x 'scripts/xml-casa';
die "expected 'xml/tools' directory to exist (and be a directory)" unless -d 'xml/tools';

$outdir = "";
foreach ( @ARGV ) {
    m|^out=(\S+)| && ($outdir = $1,next);
}

unless ( $outdir ) {
    die "expected 'tests/output-regression' directory to exist (and be a directory)" unless -d 'tests/output-regression';

    ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
    $year = ($year + 1900) % 100;
    $mon += 1;
    $outdir = sprintf("tests/output-regression/%02d%02d%02d.%02d%02d",$year,$mon,$mday,$hour,$min);
    make_path($outdir) or die "could not create $outdir";

}
die "expected output directory '$outdir' to exist (and be a directory)" unless -d $outdir;

sub find_xml {
    my $output = shift(@_);
    if ( -f $_ && m|\.xml$| ) {
        push(@$output,"$File::Find::dir/$_");
    }
}

@xml_files = ( );
find( sub { find_xml( \@xml_files ) }, 'xml/tools');

if ( -e "$outdir/xml" ) { remove_tree("$outdir/xml") or die "could not remove $outdir/xml" }
make_path("$outdir/xml") or die "could not create $outdir/xml";
if ( -e "$outdir/tool" ) { remove_tree("$outdir/tool") or die "could not remove $outdir/tool" }
make_path("$outdir/tool") or die "could not create $outdir/tool";
if ( -e "$outdir/swig" ) { remove_tree("$outdir/swig") or die "could not remove $outdir/swig" }
make_path("$outdir/swig") or die "could not create $outdir/swig";
if ( -e "$outdir/source" ) { remove_tree("$outdir/source") or die "could not remove $outdir/source" }
make_path("$outdir/source") or die "could not create $outdir/source";
if ( -e "$outdir/include" ) { remove_tree("$outdir/include") or die "could not remove $outdir/include" }
make_path("$outdir/include") or die "could not create $outdir/include";
open( $log, "> $outdir/log.txt" );

$starttime = strftime("%a %b %e %H:%M:%S %Y", localtime);
print $log "start time: $starttime\n";
print $log "input files:\n";
foreach ( sort @xml_files ) {
    print $log "    $_\n";
    copy($_,"$outdir/xml") or die "could not copy $_";
}
$cmd = "scripts/xml-casa output-c=$outdir/source output-h=$outdir/include output-i=$outdir/swig output-tool=$outdir/tool -all " . join(" ",sort @xml_files);
print $log "command: $cmd\n";
print $log "output:\n";
unless ( open( $xmlgen, "$cmd 2>&1 |" ) ){
    my $message = "could not execute the command: $!";
    print $log "$message\n";
    die $message;
}
while ( my $line = <$xmlgen> ) {
    print $log "    $line";
}
unless ( close($xmlgen) ) {
    my $message = $! ? "error closing cmd pipe: $!" : "exit status $? from cmd";
    print $log "$message\n";
    die $message;
}
close($log) or die "error closing log: $!";
