#!/usr/bin/perl -w

use strict;
use Getopt::Long;
use Tools;

my $force = '';
GetOptions("force" => \$force);

my $DIR;
opendir($DIR, ".");
while (my $dir = readdir($DIR)) {
    if (!(-d $dir)) { next; }
    if ($dir =~ /^\./) { next; }
    if (!(-e "$dir/xml")) { next; }

    process($dir);
}
close($DIR);

sub process {
    my $dir = shift;
    my $DIR;
    opendir($DIR, "$dir/xml");
    while (my $xml = readdir($DIR)) {
        if (!($xml =~ /\.xml/)) { next; }

        my $in = "$dir/xml/$xml";
        my $out;
        if ($xml eq "head.xml") {
            $out = "$dir/$dir.raw.xml";
        } elsif ($xml eq "head-simple.xml") {
            $out = "$dir/$dir.simple.raw.xml";
        } else {
            print STDERR "WARNING: Cannot parse $dir/xml/$xml\n";
            next;
        }

        my $options = getOptions($dir);
        if (!(-e $out) or $force) {
            `xsltproc $options $Tools::tools/convert2raw.xsl $in | xmllint --format - | $Tools::tools/reformat > $out`;
        } else {
            print STDERR "WARNING: $out already exists. Use --force to override\n";
        }
    }
    close($DIR);
}

sub getOptions {
    my ($dir) = @_;

    my $css;
    {
        open(F, "$dir/global.css");
        local $/;
        $css = <F>;
        close(F);
    }

    my $global = '';
    if ($css =~ /global_(\w+)\.css/sm) {
        $global = $1;
    }
    my $reset = 0;
    if ($global eq 'minimal' or $global eq 'noreset') {
        $reset = 1;
    }
    my $options = "";
    if ($global) {
        $options .= " --stringparam global $global";
    }
    if ($reset) {
        $options .= " --stringparam need-reset yes";
    }

    return $options;
}

