#!/usr/bin/env perl 
use strict;
use warnings;
use File::Spec::Functions qw/catdir catfile rel2abs/;
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" and next unless $source;

        my $dest = catfile( $to, @parts ) . '.pm';
        warn "failed to copy $source to $dest: they are the same path"
          and next
          if rel2abs($source) eq rel2abs($dest);

        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;
    }
    if (@success) {
        print 'copied modules: ', join ', ', @success;
        print "\n";
    }
    else {
        print "0 modules are copied\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
}
