#!/bin/sh

# This script implements `chroot' functionality in userland.
# It can also be used by non-root users.
#
# It provides a lot less security than the real (kernel) chroot,
# but please note that root can easily break out of a real chroot shell
# too. Neigther this trick-chroot nor the real chroot should be
# considered `safe'.

# The main purpose of this script is to show an example of how to
# work with libtricks.

# Note btw that, as the dynamic linker (/lib/ld.so-linux) is statically
# linked, it will search the libraries in the real root, not in this
# chroot environment. So, you don't have to populate ${CHROOT}/lib.

help ()
{
    echo "trick-chroot: simple implementation of chroot in userland."
    echo "     Usage: trick-chroot [--libpath path] direcotry [command]"
    echo "trick-chroot can be used both by root and non-root users."
}

while true; do
  case $1 in
    --libpath)
      shift
      LIBPATH="$1"
      ;;
    --help)
      help
      exit 0
      ;;
    --version)
      echo trick-chroot, version 0.2
      exit 0
      ;;
    *)
      break;
      ;;
  esac
  shift
done

CHROOT="`cd \"$1\" && /bin/pwd`"

if test ! -d "$CHROOT"; then
  echo First parameter must be a directory.
  help
  exit 1
fi

shift

LD_PRELOAD=${LIBPATH:-/usr/lib/libtricks}/libtricks.so.0
VPATH="-chop(\"$CHROOT\")=:$CHROOT:return(ENOENT)="

if test -z "$*"; then
  LD_PRELOAD=$LD_PRELOAD VPATH=$VPATH \
    /bin/sh
else
  LD_PRELOAD=$LD_PRELOAD VPATH=$VPATH \
    $@
fi

