#!/bin/sh -e
# v.pl DIR [PERL] -- setup virtualized Perl installation
#
# To the extent possible under law, Leah Neukirchen <leah@vuxu.org>
# has waived all copyright and related or neighboring rights to this work.
# http://creativecommons.org/publicdomain/zero/1.0/

fail() {
	echo "error: $@" 1>&2
	exit 1
}

DIR=$1
[ -n "$DIR" ] || fail "usage: v.pl DIR [PERL]"

PERL=${2:-$(command -v perl)} || fail "perl $PERL not found"
[ -d "$DIR" ] && fail "target directory $DIR exists"
mkdir "$DIR"
VER=$(perl -e 'print $^V') || fail "can't determine Perl version"

cd "$DIR"
DIR=$PWD

mkdir -p bin lib/perl5 man

cat >bin/perl <<EOF
#!/bin/sh
# $PERL $VER virtualized by v.pl on $(date)
# as $DIR/bin/perl
export PATH="$DIR/bin\${PATH:+:\${PATH}}"
export PERL5LIB="$DIR/lib/perl5\${PERL5LIB:+:\${PERL5LIB}}"
export PERL_MB_OPT="--install_base \"$DIR\""
export PERL_MM_OPT="INSTALL_BASE=$DIR"
export PERL="$DIR/bin/perl"
exec $PERL "\$@"
EOF

# Rewrite path of perl for MakeMaker to adjust shebangs,
# but note this doesn't work for #!/usr/bin/env perl:
# https://github.com/Perl-Toolchain-Gang/ExtUtils-MakeMaker/issues/58
sed -e "1i# Modified by v.pl!" \
    -e "/^perlpath/s:=.*:='$DIR/bin/perl':" \
    -e "/^startperl/s:=.*:='#!$DIR/bin/perl':" \
  $(perl -MConfig -e '$Config{perlpath}; print $INC{"Config_heavy.pl"}') \
  >$DIR/lib/perl5/Config_heavy.pl

# Use wrappers with #!/usr/bin/perl below to keep perl -S ... working.

PERLDOC=$(command -v perldoc) &&
cat >bin/perldoc <<EOF
#!$PERL
exec "$DIR/bin/perl", "$PERLDOC", @ARGV;
EOF

CPANM=$(command -v cpanm) &&
cat >bin/cpanm <<EOF
#!$PERL
exec "$DIR/bin/perl", "$CPANM", @ARGV;
EOF

chmod 0755 bin/*
