#!/usr/bin/perl
use warnings;
use strict;

# This program generates a 'Build.PL' file for the distribution from
# information in 'META.yml'.

use YAML qw( LoadFile );

my $meta = LoadFile('META.yml');

my $scripts;
my %extra_files;
{
    open my $manifest, '<', 'MANIFEST'
        or die "$0: error opening 'MANIFEST': $!\n";
    my @scripts;

    while (<$manifest>) {
        push @scripts, $1
            if m!^(bin/[^/\s]+)$!;
        $extra_files{$1} = $1
            if m!^(lib/.*\.(\w+))$! && $2 ne 'pm';
    }

    $scripts = join ' ', @scripts;
}

my $requires = module_map(%{$meta->{requires}});
my $build_requires = module_map(%{$meta->{build_requires}});
my $recommends = module_map(
    map { map { %{$_->{requires}} } values %$_ }
    @{$meta->{optional_features}},
);
my $extra_files = module_map(%extra_files);

open my $build, '>', 'Build.PL'
    or die "$0: error opening 'Build.PL' for writing: $!\n";

print $build <<EOF;
#!/usr/bin/perl
use warnings;
use strict;
require 5.8.0;

# Automatically generated by $0

use Module::Build;

# Override the 'distmeta' action so that Module::Build won't delete
# my nice hand-crafted 'META.yml' file.
my \$class = Module::Build->subclass(
    class => 'Daizu::Keep::Meta::Yml',
    code => q(
        sub ACTION_distmeta { \$_[0]->{metafile} = 'META.yml' }
    ),
);

my \$build = \$class->new(
    module_name => '$meta->{name}',
    dist_version => '$meta->{version}',
    dist_abstract => '$meta->{abstract}',
    dist_author => '$meta->{author}[0]',
    license => '$meta->{license}',

    requires => {
        $requires,
    },
    build_requires => {
        $build_requires,
    },
    recommends => {
        $recommends,
    },
    dynamic_config => $meta->{dynamic_config},

    script_files => [qw[ $scripts ]],
    extra_files => {
        $extra_files,
    },
);

\$build->add_build_element('extra');

\$build->create_build_script;
EOF

close $build
    or die "$0: error closing 'Build.PL': $!\n";


sub module_map
{
    my (%modules) = @_;
    return join ",\n        ",
           map { "'$_' => '$modules{$_}'" }
           sort
           keys %modules;
}

# vi:ts=4 sw=4 expandtab
