#!/bin/sh

# Used to run a command inside a linux user namespace, remapping uid/gid
# so that permissions may be elevated (eg like inside a container).
# May be needed for execution of certain commands / tools.
#
# NS_SETUP carries the definition of _ns_setup() across the unshare boundary.
# _ns_setup is called inside the namespace before running the cmd.

set -eu
uid=$(id -u)
: "${NS_SETUP:=_ns_setup() { :; }}"

if [ "$uid" -eq 0 ]; then
   eval "$NS_SETUP"
   _ns_setup
   "$@"
else
   # --mount as well as --user: mmdebstrap makes / rprivate and mounts
   # dev/console, which needs a mount namespace of our own. podman unshare
   # gave us both; unshare --user alone does not.
   exec unshare --user --mount --map-auto --map-root-user \
      bash -c 'eval "$NS_SETUP"; _ns_setup; "$@"' -- "$@"
fi
