#!/bin/sh
# Create local::lib environment for Perl
# - Stoned Elipot

# Default Perl
: ${PERL:=/usr/bin/perl}

# Setup $PLLDIR
_setup() {
  set -e

  # make sure we have a full pathname on perl
  case "$PERL" in
  /*) : ;;
  *) echo 1>&2 "$0: PERL environment variable must be an absolute pathname"; exit 1 ;;
  esac

  # set PLLDIR
  if [ -n "$1" ]; then
    # from command-line
    PLLDIR="$1"
  else
    # default value
    PLLDIR="$($PERL -e 'printf "$ENV{HOME}/perl5/local-%vd", $^V')"
  fi

  bindir="$PLLDIR/bin"

  # setup PLLDIR hier
  mkdir -p "$bindir"

  # download cpanm as _cpanm
  # assumes wget is available if curl is not
  if curl --version >/dev/null 2>&1; then
    curl --insecure -L -o "$bindir/_cpanm" http://cpanmin.us
  else
    wget --no-check-certificate -O "$bindir/_cpanm" http://cpanmin.us
  fi
  chmod +x "$bindir/_cpanm"
  $PERL -pi -e "s,^\#!.*,\#!$PERL, if $. == 1" "$bindir/_cpanm"

  # install local::lib and its needed dependencies
  # if $PERL already has an uptodate local::lib we need
  # to specify --reinstall to cpanm so it is really
  # installed in $PLLDIR
  "$bindir/_cpanm" -l "$PLLDIR" --reinstall $_SETUP_NOTEST local::lib 

  # create perl wrapper
  cat > "$bindir/perl" <<-EOS
	#!/bin/sh
	exec \${PERL:=$PERL} -I"$PLLDIR"/lib/perl5 -Mlocal::lib="$PLLDIR" "\$@"
	EOS
  chmod 755 "$bindir/perl"

  # create cpanm wrapper
  cat > "$bindir/cpanm" <<-EOS
	#!/bin/sh
	exec "$PLLDIR"/bin/_cpanm -l "$PLLDIR" "\$@"
	EOS
  chmod 755 "$bindir/cpanm"

  # create activate shell script
  cat > "$bindir/activate.sh" <<-EOS
	eval \$(\${PERL:=$PERL} -I"$PLLDIR"/lib/perl5 -Mlocal::lib="$PLLDIR")
	EOS

  # create deactivate shell script
  cat > "$bindir/deactivate.sh" <<-EOS
	eval \$(\${PERL:=$PERL} -I"$PLLDIR"/lib/perl5 -Mlocal::lib="--deactivate,$PLLDIR")
	EOS

  # create perldoc shell script
  cat > "$bindir/perldoc" <<-EOS
	#!/bin/sh
	eval \$($PERL -I"$PLLDIR"/lib/perl5 -Mlocal::lib="$PLLDIR")
	# if PERLDOC is not set assume perldoc is alongside PERL
	# if not default to /usr/bin/perldoc
	: \${PERLDOC:=${PERL}doc}
	test -x "\$PERLDOC" || PERLDOC=/usr/bin/perldoc
	exec \${PERLDOC} "\$@"
	EOS
  chmod 755 "$bindir/perldoc"

  echo "Perl environment $PLLDIR initiated."
}

# Main
case "$1" in
  # Setup local lib environment for $PERL without running Perl module tests
  --notest|--no-test|-n)
  shift
  _SETUP_NOTEST="--notest"
  _setup "$@"
  ;;

  # Setup local lib environment for $PERL
  *)
  _SETUP_NOTEST=
  _setup "$@"
  ;;
esac

# vim: ft=sh