#!/usr/bin/perl
use strict;
use File::Find;
use Yandex::YCssJs;

my $PROJECT = '[% PROJECT %]';
my ($CURDIR, $DESTDIR) = @ARGV;
$CURDIR =~ s#/*$#/#;
my $PROJECT_DESTDIR = "$DESTDIR/usr/local/www/$PROJECT.static.yandex.net";

sub xsystem {
    system @_;
    die "@_ failed" if $? != 0;
}

my %dirs;
my %files;

find({ wanted => \&process, no_chdir => 1}, "$CURDIR");
sub process {
    my $file = $_;
    if (!($file =~ /\.([% FILE_TYPES %])$/)) { return; }
    if ($file =~ m#(?:^|/)debian/#) { return; }

    $file =~ s/^\Q$CURDIR\E// or die "file '$file' found in '$CURDIR'";
    $files{$file}++;

    my $dir = $file;
    $dir =~ s#[^/]+$##;
    $dirs{$dir}++;
}

xsystem("mkdir -p $PROJECT_DESTDIR/$_") for (keys %dirs);
xsystem("cp $CURDIR/$_ $PROJECT_DESTDIR/$_") for (keys %files);
xsystem("mkdir -p $DESTDIR/usr/local/www/static.yandex.net");
xsystem("ln -sf ../$PROJECT.static.yandex.net/ $DESTDIR/usr/local/www/static.yandex.net/$PROJECT");

my @files4ycssjs = grep { is_4ycssjs($_); } keys %files;
sub is_4ycssjs {
    my ($file) = @_;
    return 0 if ($file =~ m#(?:^|/)lego/#);
    return 0 if ($file !~ /\.(css|js)$/);
    return 1;
}

my $ycssjs = new Yandex::YCssJs;
$ycssjs->process(map {"$PROJECT_DESTDIR/$_"} @files4ycssjs);


