#!perl
use strict;
use warnings;
use utf8;

use lib 'lib';
use Archive::Zip qw( :ERROR_CODES :CONSTANTS );
use Data::Dumper;
use File::Basename;
use File::Temp;
use LWP;
use Text::Xslate;

my $xslate = Text::Xslate->new(
    syntax    => 'TTerse',
    module    => ['Data::Dumper'],
    type      => 'text',
    tag_start => '<%',
    tag_end   => '%>',
);
my $ua = LWP::UserAgent->new();

local $Data::Dumper::Terse = 1;

get_bootstrap();
get_jQuery();

exit(0);

sub get_bootstrap {
    my $files = {};

    print "--> Fetching twitter bootstrap\n";

    my $zip_url = 'http://twitter.github.io/bootstrap/assets/bootstrap.zip';
    my $tmpdir = File::Temp::tempdir(CLEANUP => 1);
    my $tmp = "$tmpdir/bootstrap.zip";

    print "Download zip files to $tmp\n";

    my $res = $ua->mirror($zip_url, $tmp);
    $res->is_success or die $res->status_line;
    -s $tmp > 0 or die "File is too short";
    my $zip = Archive::Zip->new();
    $zip->read($tmp) == AZ_OK or die "Cannot read zip file";

    for my $member ($zip->members()) {
        next if $member->isDirectory;
        my $contents = $member->contents();
        $files->{$member->fileName} = $contents;
    }

    local $Data::Dumper::Useqq = 1;
    local $Data::Dumper::Sortkeys = 1;

    my $content = $xslate->render_string(<<'...', {script => $0, content => Dumper($files)});
# This file is generated by <% script %>. Do not edit manually.
package Nephia::Setup::Bootstrap::TwitterBootstrap;
use strict;
use warnings;

sub files {
    <% content %>
}

1;
...

    open my $fh, '>:utf8', 'lib/Nephia/Setup/Bootstrap/TwitterBootstrap.pm';
    print {$fh} $content;
    close $fh;

    eval "use Nephia::Setup::Bootstrap::TwitterBootstrap;";
    die $@ if $@;

    print "Success!\n";
}

sub get_jQuery {
    print "--> Fetching jQuery\n";

    my $url = 'http://code.jquery.com/jquery.js';
    my $res = $ua->get($url);
    $res->is_success or die $res->status_line;

    my $jquery = $res->decoded_content;

    open my $fh, '>:utf8', 'lib/Nephia/Setup/Bootstrap/jQuery.pm';
    print {$fh} $xslate->render_string(<<'...', +{ file => $0, basename => basename($url), data => Dumper({ 'js/' . basename($url) => $jquery})});
package Nephia::Setup::Bootstrap::jQuery;
use strict;
use warnings;

sub files {
    return <% data %>;
}

1;
...
    close $fh;

    eval "use Nephia::Setup::Bootstrap::jQuery;";
    die $@ if $@;

    print "Success!\n";
}
