#!/usr/bin/perl -w

use strict;

use Cwd 'abs_path';
use File::Basename;

BEGIN {
    my (undef, $tools) = fileparse(abs_path($0));
    $tools =~ s{/[^/]*$}{};
    push(@INC, $tools);
}

use Tools;
use File::Find;
use Getopt::Long;

my $paths;
my $mode;
my $noformat;

GetOptions( 'paths=s' => \$paths, 'mode=s' => \$mode, 'no-lint-format' => \$noformat );
if (!$paths) { die usage(); }
if (!$mode) { $mode = 'all'; }

my @locales = qw(ru en uk be kk tt az tr); # первый элемент -- дефолтная локаль

my $file = shift;

if ($file) {
    while ($file) {
        if (-d $file) {
            process_dir($file);
        } elsif (-f $file) {
            my ($file, $dir) = fileparse(abs_path($file));
            process_file($dir, $file);
        } else {
            die "$file not file or directory";
        }

        $file = shift;
    }
} else {
    find({ wanted => \&process, no_chdir => 1 }, ".");
}

sub process {
    my $dir = $_;

    if (!(-d $dir)) { return; }
    if ($dir =~ /\.svn/) { return; }

    process_dir($dir);
}

sub process_dir {
    my $dir = shift;

    # print STDERR "rebuilding: $dir";

    my $DIR;
    opendir($DIR, "$dir");
    while (my $xml = readdir($DIR)) {
        process_file($dir, $xml);
    }
    close($DIR);

    # print STDERR " done\n";
}

sub process_file {
    my ($dir, $xml) = @_;

    if ($xml =~ /\.raw\.xml$/) {
        my $in = "$dir/$xml";
        my $options = Tools::options($in);
        my $needformat = ($noformat) ? "" : '--format';

        my $out = $xml;
        $out =~ s/\.raw\.xml$//;

        system("perl -I$Tools::tools $Tools::tools/xml2paths --input $dir/$out.raw.xml --paths $paths --mode convert2xml") == 0 or die("ERROR: xml2paths failed");

        for my $locale ( ($options->{'need-localization'}) ? @locales : @locales[0,0] ) {
            system("bash -c 'set -o pipefail; xsltproc --xinclude --stringparam locale $locale $dir/$out.convert2xml.xsl $in | xmllint $needformat - | $Tools::tools/reformat > $dir/$out.$locale.xml'") == 0 or die("ERROR: xsltproc failed");
        }
        if (!(-e "$dir/$out.xml")) {
            system("cd $dir; ln -sf $out.ru.xml $out.xml") == 0 or die("ERROR: ln failed");
        }
        system("rm $dir/$out.convert2xml.xsl");
        system("perl -I$Tools::tools $Tools::tools/xml2paths --input $dir/$out.xml --paths $paths --mode $mode") == 0 or die("ERROR: xml2paths failed");
    }
}

sub usage {
    return <<USAGE;
USAGE:
    > rebuild --paths PATHS [file or directory] [file or directory] …

    for example:
    > rebuild --paths lego/blocks:lego/services/fotki/blocks:blocks
    > rebuild --paths lego/blocks:lego/services/fotki/blocks:blocks index.raw.xml
    > rebuild --paths lego/blocks:lego/services/fotki/blocks:blocks pages
USAGE
}

