#!/bin/sh

usage () {
cat - >&2 <<EOF
fakeroot-like wrapper for pseudo, create a fake root environment.
   usage: fakeroot [-l|--lib fakerootlib] [-f|--faked fakedbin]
                   [-i file] [-s file] [-u|--unknown-is-real]
		   [-b|--fd-base fd] [-h|--help] [-v|--version]
                   [--] [command]
EOF
  exit 1
}

stderr ()
{
  local i
  for i
  do
      echo >&2 "fakeroot: $i"
  done
}

fatal ()
{
  stderr "$@"
  exit 1
}

# strip /bin/fakeroot to find install prefix
FAKEROOT_PREFIX=/usr
FAKEROOT_BINDIR=/usr/bin

KEEPSTATEDIR=0

GETOPTTEST=`getopt -T`
if test "$?" -eq 4; then # GNU getopt
    FAKE_TEMP=`getopt -l lib: -l faked: -l unknown-is-real -l fd-base: -l version -l help -- +l:f:i:s:ub:vh "$@"`
else
    FAKE_TEMP=`getopt l:f:i:s:ub:vh "$@"`
fi

if [ "$?" -ne 0 ]
then
  usage
fi

eval set -- "$FAKE_TEMP"

while test "X$1" != "X--"; do
  case "$1" in
    -l|--lib)
       shift
       ;;
    -f|--faked)
       shift
       ;;
    -i)
       shift
       if test -d "$1"
       then
         PSEUDO_LOCALSTATEDIR="$(readlink -m "$1")"
       else
         stderr "local state dir \`$1' doesn't exist."
       fi
       ;;
    -s)
       shift
       if mkdir -p "$1"
       then
         PSEUDO_LOCALSTATEDIR="$(readlink -m "$1")"
         KEEPSTATEDIR=1
       else
         stderr "local state dir \`$1' could not be created."
       fi
       ;;
    -u|--unknown-is-real)
       ;;
    -b|--fd-base)
       shift
       ;;
    -v|--version)
       printf "fakeroot wrapper for "
       pseudo -V
       exit 0
       ;;
    -h|--help)
       usage
       ;;
  esac
  shift
done

shift #get rid of the '--'

if [ -z "$PSEUDO_LOCALSTATEDIR" ]
    then
    UID=`id -u`
    if [ -d /run/user/$UID -a -w /run/user/$UID ]
    then
        PSEUDO_LOCALSTATEDIR=/run/user/$UID/pseudo/$$
        mkdir -p "$PSEUDO_LOCALSTATEDIR"
    else
        PSEUDO_LOCALSTATEDIR=/tmp/pseudo.$UID/$$
        if ! mkdir -p "$PSEUDO_LOCALSTATEDIR"
        then
            fatal "Could not find a suitable state dir"
        fi
    fi
fi

export PSEUDO_PREFIX=/usr
export PSEUDO_LOCALSTATEDIR

if test -n "$FAKEROOTKEY"
then
    fatal "FAKEROOTKEY set to $FAKEROOTKEY" \
          "nested operation not yet supported"
fi

unset FAKEROOTKEY
export FAKEROOTKEY=pseudo

export LD_PRELOAD="/usr/lib/aarch64-linux-gnu/pseudo/libpseudo.so"
if test -z "$*"; then
    ${SHELL:-/bin/sh}
    RESULT=$?
else
    "$@"
    RESULT=$?
fi

if [ "$KEEPSTATEDIR" -ne 1 ]
then
    rm -rf "$PSEUDO_LOCALSTATEDIR"
fi

exit $RESULT

# Local Variables:
# mode: shell-script
# End:
