#!/bin/sh
# vim: set ts=2 sts=2 sw=2 expandtab smarttab filetype=perl:
#! -*-perl-*-
eval 'exec perl -x -wS $0 ${1+"$@"}'
  if 0;

# PODNAME: rlibperl
# ABSTRACT: Execute perl prepending relative lib to @INC

use strict;
use warnings;
use FindBin;    # core
use File::Spec::Functions qw( catdir catpath splitdir splitpath ); # core
use Config;     # core

# __FILE__ can be relative, use FindBin to make sure we get enough path to go up

# FindBin::Bin is a dir, so set $no_file to true for reliability
my ($vol, $dirs, $file) = splitpath($FindBin::Bin, 1);
my @base = splitdir($dirs);
my @inc;

# this looks more complicated than it really is

  my $bin = pop @base;

  # ./lib
  my @sets = [ [$bin, qw(lib)] ];

  # local::lib uses ../lib/perl5
  my $local_lib = [
    [qw(lib perl5)],
  ];

  # the most likely structure is bin/../lib
  # but if we're not in a bin/ it might be a project root
  # so look for ./lib before looking for ../lib

  $bin =~ /^(bin|scripts?)$/i
    ? unshift(@sets, $local_lib)
    :    push(@sets, $local_lib);

  # if those fail try ../lib (project-specific bin/)
  push @sets, [ [qw(lib)] ];

  # should we be looking for $archname to determine the order we check?
  # should we be looking for ./lib/perl5 ? [ map { [ $bin, @$_ ] } @$local_lib ]
  # should we be looking for blib?  (blib/lib, blib/arch)?

  my %current = map { ($_ => 1) } @INC; # uniq
  LIB: foreach my $set ( @sets ){
    @inc =
      grep { -d $_ && !exists($current{$_}) }
      map  { catpath($vol, catdir(@base, @$_), '') }
        @$set;
    last LIB if @inc;
  }

# see perldoc description of perlvar $^X
my $perl = $Config{perlpath};
if ($^O ne 'VMS') {
  $perl .= $Config{_exe}
    unless $perl =~ m/$Config{_exe}$/i;
}

# put current bin in path so perl -S will find it
$ENV{PATH} = $FindBin::Bin . $Config{path_sep} . $ENV{PATH};

# re-invoke perl with the the lib dirs prepended
exec($perl, (map { '-I' . $_ } @inc), @ARGV);
die "Failed to execute '$perl': $!";

# IDEA: similar to ylib, could read a ~/.file for extra paths to include, possibly multiple keyed on location of script


__END__
=pod

=for :stopwords Randy Stauner ACKNOWLEDGEMENTS

=encoding utf-8

=head1 NAME

rlibperl - Execute perl prepending relative lib to @INC

=head1 VERSION

version 0.400

=head1 SEE ALSO

=over 4

=item *

L<App::rlibperl> for documentation

=item *

L<App::rbinperl> which uses this script to execute another perl script in the same dir

=back

=head1 AUTHOR

Randy Stauner <rwstauner@cpan.org>

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2011 by Randy Stauner.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut

