#!perl

# Quickie utility for squashing together the parts for the standalone version

use warnings;
use strict;

use File::Next;

# make clear that ack-standalone is not supposed to be edited
my $NO_EDIT_COMMENT = <<'EOCOMMENT';
#
# This standalone version of ack is generated code.
# Please DO NOT EDIT or send patches for it.
#
EOCOMMENT

my $code;
for my $arg ( @ARGV ) {
    my $filename = $arg;
    if ( $arg =~ /::/ ) {
        my $key = "$arg.pm";
        $key =~ s{::}{/}g;
        $filename = $INC{$key} or die "Can't find the file for $arg";
    }

    warn "Reading $filename\n";
    open( my $fh, '<', $filename ) or die "Can't open $filename: $!";

    while ( <$fh> ) {
        next if /^use (File::Next|App::Ack)/;

        # See if we're in module POD blocks
        my $skip = ($filename ne 'ack') && (/^=/ .. /^=cut/);
        if ( !$skip ) {
            # Replace the shebang line and append 'no edit' comment
            if ( s{^#!.+}{#!/usr/bin/env perl} ) {
                $_ .= $NO_EDIT_COMMENT;
            }

            # Remove Perl::Critic comments.
            # I'd like to remove all comments, but this is a start
            s{\s*##.+critic.*}{};

            $code .= $_;
        }
    }
    close $fh;
}

for my $unused_func ( qw( dirs everything ) ) {
    $code =~ s/^sub $unused_func\b.*?^}//sm; # It's OK if we can't find it
}
print $code;

exit 0;
