#!/bin/sh

# $Id: /svn/trunk/scripts/fakechroot.in 160 2005-09-08T15:35:16.405737Z dexter  $

usage () {
cat - >&2 <<EOF
fakechroot, create a fake chroot environment.
   usage: fakechroot [-l|--lib fakechrootlib]
                     [-s|--use-system-libs]
                     [-h|--help] [-v|--version]
                     [--] [command]
EOF
  exit 1
}

LIB=lib@fakechroot_transformed@.so
PATHS=@libpath@

FAKECHROOT=true
export FAKECHROOT

FAKECHROOT_VERSION=@VERSION@
export FAKECHROOT_VERSION

libfound=no

GETOPTEST=`getopt --version`
case $GETOPTEST in
getopt*) # GNU getopt
    TEMP=`getopt -l lib: -l use-system-libs -l version -l help -- +l:svh "$@"`
    ;;
*) # POSIX getopt ?
    TEMP=`getopt l:svh "$@"`
    ;;
esac

if test "$?" -ne 0; then
  usage
fi

eval set -- "$TEMP"

while test "X$1" != "X--"; do
  case "$1" in
    -l|--lib)
       shift
       LIB=`eval echo "$1"`
       PATHS=
       ;;
    -v|--version)
       echo "fakechroot version @VERSION@"
       exit 0
       ;;
    -s|--use-system-libs)
       PATHS="$PATHS:/usr/lib:/lib"
       ;;
    -h|--help)
       usage
       ;;
  esac
  shift
done

shift #get rid of the '--'

# make sure the preload is available
if [ -n "$PATHS" ]
then
    for dir in `echo $PATHS | sed 's/:/ /g'`
    do
	if test -r "$dir/$LIB"
	then
	    libfound=yes
	fi
    done
else
    if test -r "$LIB"
    then
	libfound=yes
    fi
fi

if test $libfound = no
then
    echo >&2 "fakechroot: preload library not found, aborting."
    exit 1
fi

# Keep other library paths
if test -n "$LD_LIBRARY_PATH"; then
  PATHS="$PATHS:$LD_LIBRARY_PATH"
fi
# ...and preloaded libs
if test -n "$LD_PRELOAD"; then
  LIB="$LIB $LD_PRELOAD"
fi

if test -z "$*"; then
  LD_LIBRARY_PATH="$PATHS"
  LD_PRELOAD="$LIB"
  export LD_LIBRARY_PATH LD_PRELOAD
  exec ${SHELL:-/bin/sh}
else
  LD_LIBRARY_PATH="$PATHS"
  LD_PRELOAD="$LIB"
  export LD_LIBRARY_PATH LD_PRELOAD
  exec "$@"
fi

exit 1
