#!/usr/bin/env perl
########################################################################
# Build a sandbox with a directory symlink and a file symlink, run one
# probe program through each path, and show $Bin_l, $Bin_p, and the
# lib dirs and etc/app.conf files each walk finds.  See POD.
########################################################################

use v5.40;

use Cwd                     qw( abs_path getcwd );
use File::Basename          qw( dirname );
use File::Path              qw( make_path );
use File::Spec::Functions   qw( catdir catfile rel2abs );
use File::Temp              qw( tempdir );

# loaded here only to find the lib the probe should use.

use FindBin::Bin ();

########################################################################
# probe: the program run through each path
########################################################################

my $probe_code  = <<~'PROBE';
    #!/usr/bin/env perl
    use v5.40;

    use FindBin::Bin    qw( $Bin $Bin_l $Bin_p );

    use FindBin::libs   qw( export=lib_p           nouse nofail );
    use FindBin::libs   qw( export=lib_l noabspath nouse nofail );

    use FindBin::Files  qw( file=etc/app.conf export=conf_p           nofail );
    use FindBin::Files  qw( file=etc/app.conf export=conf_l noabspath nofail );

    my @rowz
    = (
        [ '$Bin'                    => [ $Bin   ]   ]
      , [ '$Bin_l'                  => [ $Bin_l ]   ]
      , [ '$Bin_p'                  => [ $Bin_p ]   ]
      , [ 'lib,      abspath'       => \@lib_p      ]
      , [ 'lib,      noabspath'     => \@lib_l      ]
      , [ 'app.conf, abspath'       => \@conf_p     ]
      , [ 'app.conf, noabspath'     => \@conf_l     ]
    );

    for( @rowz )
    {
        my ( $name, $pathz ) = $_->@*;

        printf "    %-20s %s\n", $name, join( ' ', $pathz->@* ) || '(none)';
    }
    PROBE

########################################################################
# utility subs
########################################################################

my $write_file
= sub( $path, $text )
{
    open my $fh, '>', $path
    or die "Cannot write '$path': $!\n";

    print $fh $text;

    close $fh
    or die "Cannot close '$path': $!\n";
};

my $make_link
= sub( $target, $link )
{
    symlink $target, $link
    or die "Cannot symlink '$link' -> '$target': $!\n";
};

########################################################################
# build the sandbox
#
#   $ROOT/work/projects/            physical tree
#       lib/
#       etc/app.conf
#       app/bin/script              the probe
#
#   $ROOT/home/user/                logical tree
#       lib/
#       etc/app.conf
#       app -> $ROOT/work/projects/app
#       bin/script -> $ROOT/work/projects/app/bin/script
#
# abs_path: if the temp dir is itself below a symlink (e.g., /tmp on
# macOS) the "real path" run would otherwise not be physical.
########################################################################

my $lib_d   = rel2abs dirname dirname $INC{ 'FindBin/Bin.pm' };
my $start_d = getcwd;

my $root    = abs_path tempdir( CLEANUP => 1 );
my $work_d  = catdir $root, qw( work projects );
my $home_d  = catdir $root, qw( home user );
my $app_d   = catdir $work_d, 'app';
my $probe   = catfile $app_d, qw( bin script );

make_path
    catdir( $work_d, 'lib' )
  , catdir( $work_d, 'etc' )
  , catdir( $app_d,  'bin' )
  , catdir( $home_d, 'lib' )
  , catdir( $home_d, 'etc' )
  , catdir( $home_d, 'bin' )
;

$write_file->( catfile( $work_d, qw( etc app.conf ) ), "# defaults\n"  );
$write_file->( catfile( $home_d, qw( etc app.conf ) ), "# overrides\n" );
$write_file->( $probe, $probe_code );

chmod 0755, $probe
or die "Cannot chmod '$probe': $!\n";

$make_link->( $app_d, catdir( $home_d, 'app' ) );
$make_link->( $probe, catfile( $home_d, qw( bin script ) ) );

########################################################################
# run the probe: [ name, working directory, program path ]
########################################################################

my @runz
= (
    [
        'real path'
      , $root
      , $probe
    ]
  , [
        'directory symlink'
      , $root
      , catfile( $home_d, qw( app bin script ) )
    ]
  , [
        'file symlink'
      , $root
      , catfile( $home_d, qw( bin script ) )
    ]
  , [
        'relative path, working directory via the directory symlink'
      , catdir( $home_d, qw( app bin ) )
      , catfile( '.', 'script' )
    ]
);

say "Sandbox: \$ROOT = $root";

for my $run ( @runz )
{
    my ( $name, $cwd, $prog ) = $run->@*;

    # builtin chdir leaves $PWD stale; set it to the logical path the
    # way a shell's "cd" does, so pwd() and $Bin_l keep the symlink.

    chdir $cwd
    or die "Cannot chdir '$cwd': $!\n";

    local $ENV{ PWD } = $cwd;

    open my $fh, '-|', $^X, "-I$lib_d", $prog
    or die "Cannot run '$^X' on '$prog': $!\n";

    my $output  = do { local $/; readline $fh };

    close $fh
    or die "Failed: '$^X' on '$prog' exited with status $?\n";

    s{ \Q$root\E }{\$ROOT}xg
    for $name, $cwd, $prog, $output;

    say '';
    say "$name:";
    say "    cd $cwd; $prog";
    say '';
    print $output;
}

# leave the sandbox so CLEANUP can remove it.

chdir $start_d
or die "Cannot chdir '$start_d': $!\n";

__END__

=head1 NAME

symlink_paths - show $Bin_l and $Bin_p through directory and file symlinks

=head1 SYNOPSIS

    perl example/symlink_paths

=head1 DESCRIPTION

Builds a sandbox in a temporary directory, writes a small probe
program into it, and runs the probe four ways: by its real path,
through a directory symlink, through a file symlink, and by a relative
path from a working directory reached through the directory symlink.

The probe prints C<$Bin>, C<$Bin_l> and C<$Bin_p> from
L<FindBin::Bin>, the C<lib> directories L<FindBin::libs> finds with
C<abspath> and with C<noabspath>, and the C<etc/app.conf> files
L<FindBin::Files> finds each way.  The sandbox is removed on exit.

=head2 The sandbox

    $ROOT/work/projects/                    physical tree
    +-- lib/
    +-- etc/
    |   \-- app.conf                        defaults
    \-- app/
        \-- bin/
            \-- script                      the probe

    $ROOT/home/user/                        logical tree
    +-- lib/
    +-- etc/
    |   \-- app.conf                        local overrides
    +-- app -> $ROOT/work/projects/app      directory symlink
    \-- bin/
        \-- script -> $ROOT/work/projects/app/bin/script
                                            file symlink

The probe runs from:

    use FindBin::Bin    qw( $Bin $Bin_l $Bin_p );

    use FindBin::libs   qw( export=lib_p           nouse nofail );
    use FindBin::libs   qw( export=lib_l noabspath nouse nofail );

    use FindBin::Files  qw( file=etc/app.conf export=conf_p           nofail );
    use FindBin::Files  qw( file=etc/app.conf export=conf_l noabspath nofail );

C<nouse> keeps the lib dirs out of C<@INC>: the exported lists show
what each walk found.

=head2 Output

    real path:
        cd $ROOT; $ROOT/work/projects/app/bin/script

        $Bin                 $ROOT/work/projects/app/bin
        $Bin_l               $ROOT/work/projects/app/bin
        $Bin_p               $ROOT/work/projects/app/bin
        lib,      abspath    $ROOT/work/projects/lib
        lib,      noabspath  $ROOT/work/projects/lib
        app.conf, abspath    $ROOT/work/projects/etc/app.conf
        app.conf, noabspath  $ROOT/work/projects/etc/app.conf

    directory symlink:
        cd $ROOT; $ROOT/home/user/app/bin/script

        $Bin                 $ROOT/work/projects/app/bin
        $Bin_l               $ROOT/home/user/app/bin
        $Bin_p               $ROOT/work/projects/app/bin
        lib,      abspath    $ROOT/work/projects/lib
        lib,      noabspath  $ROOT/home/user/lib
        app.conf, abspath    $ROOT/work/projects/etc/app.conf
        app.conf, noabspath  $ROOT/home/user/etc/app.conf

    file symlink:
        cd $ROOT; $ROOT/home/user/bin/script

        $Bin                 $ROOT/work/projects/app/bin
        $Bin_l               $ROOT/home/user/bin
        $Bin_p               $ROOT/work/projects/app/bin
        lib,      abspath    $ROOT/work/projects/lib
        lib,      noabspath  $ROOT/home/user/lib
        app.conf, abspath    $ROOT/work/projects/etc/app.conf
        app.conf, noabspath  $ROOT/home/user/etc/app.conf

    relative path, working directory via the directory symlink:
        cd $ROOT/home/user/app/bin; ./script

        $Bin                 $ROOT/work/projects/app/bin
        $Bin_l               $ROOT/home/user/app/bin
        $Bin_p               $ROOT/work/projects/app/bin
        lib,      abspath    $ROOT/work/projects/lib
        lib,      noabspath  $ROOT/home/user/lib
        app.conf, abspath    $ROOT/work/projects/etc/app.conf
        app.conf, noabspath  $ROOT/home/user/etc/app.conf

=head2 What it shows

=over 4

=item Real path

With no symlinks in C<$0> the two are the same and both walks find
the same dirs.

=item Directory symlink

C<$Bin_l> keeps the symlink, so the C<noabspath> walk goes up through
C<$ROOT/home/user> and finds the sandbox C<lib> and C<app.conf>.
C<$Bin_p> resolves it, so the C<abspath> walk finds the project's.
This is the regression-testing layout from L<FindBin::libs>: a
sandbox with its own C<lib> and C<etc> and a symlink to the code
under test.

=item File symlink

The usual install: a program in C<~/bin> or C</usr/local/bin> that is
a symlink to the real file.  C<$Bin_l> is the directory holding the
symlink, C<$Bin_p> the one holding the file.  The C<abspath> default
finds the C<lib> next to the real program wherever it is linked from.

=item Relative path

A relative C<$0> is resolved against C<pwd()>, which uses
C<$ENV{ PWD }> when it names the working directory, as it does after
a shell's C<cd>.  C<$Bin_l> keeps the symlink from the working
directory.

=back

In every case C<$Bin> is C<$Bin_p>: pass C<noabspath> to
L<FindBin::Bin> to make it C<$Bin_l>.

=head1 SEE ALSO

L<FindBin::Bin>, L<FindBin::libs>, L<FindBin::Files>,
F<example/dual_lib_paths>, F<example/layered_etc>

