#!/usr/bin/env perl
use strict;
use warnings;
use File::Find;
use File::Slurp 'slurp';
use List::MoreUtils 'uniq';
use autodie;

unlink 'lib/Mouse/Tiny.pm'
    if -e 'lib/Mouse/Tiny.pm';

my @files;

find({
    wanted => sub {
        push @files, $_
            if -f $_
            && !/Squirrel/
            && !/\bouse/
            && !/\.sw[po]$/
    },
    no_chdir => 1,
}, 'lib');

my $mouse_tiny = '';

for my $file (uniq 'lib/Mouse/Util.pm', sort @files) {
    my $contents = slurp $file;

    $contents =~ s/__END__\b.*//s;          # remove documentation
    $contents =~ s/1;\n*$//;                # remove success indicator

    $contents =~ s/^use Mouse\S*\s*\n//mg;  # we're already loading everything
    $contents =~ s/^use (Mouse\S*)\s*(.+);/BEGIN { $1->import($2) }/mg;

    $mouse_tiny .= $contents;
}

open my $handle, '>lib/Mouse/Tiny.pm' or die "Can't write lib/Mouse/Tiny.pm: $!";

print { $handle } << 'EOF';
# THIS FILE IS AUTOGENERATED!

# if regular Mouse is loaded, bail out
unless ($INC{'Mouse.pm'}) {
eval <<'END_OF_TINY';

# tell Perl we already have all of the Mouse files loaded:
EOF

for my $file (@files) {
    (my $inc = $file) =~ s{^lib/}{};
    print { $handle } "\$INC{'$inc'} = __FILE__;\n";
}

print { $handle } "\n# and now their contents\n\n";

print { $handle } $mouse_tiny;

print { $handle } "END_OF_TINY\n} #unless\n\n";

print { $handle } << 'EOF';
package Mouse::Tiny;
use base 'Mouse';

EOF

print { $handle } "1;\n\n";

