package ModuleBuildBuilder;

use strict;
use Module::Build;
use vars qw(@ISA);
@ISA = qw(Module::Build);

sub ACTION_distdir {
  my $self = shift;
  $self->SUPER::ACTION_distdir(@_);
  
  my $build_pl       = File::Spec->catfile($self->dist_dir, qw(Build.PL));
  my $build_pm       = File::Spec->catfile($self->dist_dir, qw(lib Module Build.pm));
  my $base_pm        = File::Spec->catfile($self->dist_dir, qw(lib Module Build Base.pm));
  my $authoring_pod  = File::Spec->catfile($self->dist_dir, qw(lib Module Build Authoring.pod));

  open my($fh), $base_pm or die "Couldn't read $base_pm: $!";
  my %subs = map {$_,1} map +(/^\s*sub (\w+)/)[0], <$fh>;

  # Replace "<autogenerated_accessors>" with some POD lists
  my @need_doc = sort grep !$subs{$_}, $self->valid_properties;
  $self->run_perl_command(['-pi',
			   '-e',
			   qq[s{<autogenerated_accessors>}{ join "\\n\\n", map "=item \$_()", qw(@need_doc) }e],
			   $authoring_pod]);

  # Replace "<action_list>" with a list of actions
  my $action_text = $self->_action_listing(scalar $self->known_actions);
  $self->run_perl_command(['-pi', '-e', qq[s{<action_list>}{$action_text}], $build_pm]);

  # Finally, sneakily rewrite the Build.PL to use a vanilla
  # Module::Build object instead of a ModuleBuildBuilder.
  $self->run_perl_command(['-pi', '-e', qq[BEGIN{\$/=undef} s{<remove_me>.*</remove_me>}{}gs], $build_pl]);
  $self->run_perl_command(['-pi', '-e', qq[s{ModuleBuildBuilder}{Module::Build}gs], $build_pl]);
}
