#!/usr/bin/env perl 
use strict;
use warnings;
use File::Spec::Functions qw/catdir/;
use File::Path 'mkpath';
use File::Copy qw(copy);
@ARGV = grep { defined } @ARGV;
undef @ARGV if grep { /^-/ } @ARGV; # force to show usage if found -

if (@ARGV) {
    my $to = $ENV{APP_MODULES_HERE} || '.';
    my @success;
    for my $mod (@ARGV) {
        eval "require $mod" or warn "failed to require $mod" and next;

        my @parts = split /::/, $mod;
        my $inc = join( '/', @parts ) . '.pm';
        my $source = $INC{$inc};
        warn "failed to fild source of $mod" && next unless $source;
        my $here =
          catdir( $to, @parts[ 0 .. $#parts - 1 ] );
        mkpath($here)
          or warn "failed to make path $here: $!" and next
          unless -e $here;
        copy( $source, $here ) or warn "failed to copy $source to $here: $!";
        push @success, $mod;
    }
    print 'copied modules: ', join ', ', @success;
    print "\n";
}
else {
    print <<'EOF';
USAGE: mhere Module [ ... ]
EXAMPLES:
    mhere Carp                                    # copy Carp.pm in @INC to cwd
    mhere Carp CGI                                # copy both Carp.pm and CGI.pm
    APP_MODULES_HERE=outlib mhere Carp            # copy to outlib dir in cwd
    APP_MODULES_HERE=/tmp/ mhere Carp             # copy to /tmp/
EOF
}
