#!/usr/bin/perl -w

use strict;

use Tools;
use File::Path;

my $dir = shift;
opendir(DIR, $dir) or die "ERROR: Cannot open $dir";

open(G, ">$dir/index.xml");
print G <<XML;
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="../common.xsl" type="text/xsl"?>

<page xmlns:lego="https://lego.yandex-team.ru" xmlns:xi="http://www.w3.org/2001/XInclude">

    <xi:include href="../common-frame.xml"/>

    <examples>
XML
while (my $file = readdir(DIR)) {
    if ($file !~ /\.xml$/ || $file eq "index.xml") { next; }
    $file =~ s/\.xml$//;
    gen($file);
    print G <<XML;
        <example>frames/$file</example>
XML
}
closedir(DIR);
print G <<XML;
    </examples>

</page>
XML
close(F);

sub gen {
    my $file = shift;

    mkpath("$dir/frames/$file");

    my ($id) = split(/\./, $file);

    `perl -I$Tools::tools $Tools::tools/xml2paths --input $dir/$file.xml --output $dir/frames/$file/imports`;

    my $xml = "$dir/frames/$file/index.xml";
    if (!(-e $xml)) {
        open(F, ">$xml");
        print F <<XML;
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="index.xsl" type="text/xsl"?>

<page xmlns:lego="https://lego.yandex-team.ru" xmlns:xi="http://www.w3.org/2001/XInclude">

    <xi:include href="../../../common-frame.xml"/>

    <lego:b-example>
        <lego:title>$file</lego:title>
        <lego:description></lego:description>
        <lego:content>
            <xi:include href="../../$file.xml"/>
        </lego:content>
    </lego:b-example>

</page>
XML
        close(F);
    }
    else { print "WARNING: $xml already exists\n"; }

    my $xsl = "$dir/frames/$file/index.xsl";
    if (!(-e $xsl)) {
        open(F, ">$xsl");
        print F <<XSL;
<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:lego="https://lego.yandex-team.ru"
    exclude-result-prefixes=" lego "
    version="1.0">

<xsl:import href="../../../common-frame.xsl"/>
<xsl:import href="imports.xsl"/>

<xsl:strip-space elements="*"/>

<!-- ############################################################################################################## -->

XSL
    if ($id) { print F <<XSL;
<xsl:template match="/" mode="lego:params">
    <lego:id>$id</lego:id>
</xsl:template>

XSL
    }
print F <<XSL;
</xsl:stylesheet>
XSL
        close(F);
    }
    else { print "WARNING: $xsl already exists\n"; }
}

