#!/command/execlineb -s0
s6-envdir env
multisubstitute {
	importas -i -u CONTAINER_NAME CONTAINER_NAME
	importas -i -u CONTAINER_USER CONTAINER_USER
}
backtick -in CONTAINER_USER_HOME { homeof $CONTAINER_USER }
multisubstitute {
	importas -i -u CONTAINER_USER_HOME CONTAINER_USER_HOME
	define CONTAINER_TMPFS /run/containers/${CONTAINER_NAME}.sysroot
	define -s tmpfs_dirs "home run tmp inbox run/inbox tmp/.X11-unix"
}

getpid NS_PID
foreground {
	importas -i NS_PID NS_PID
	if { test -d /run/cgroup2 }
	if { mkdir -p /run/cgroup2/containers/${CONTAINER_USER}/${CONTAINER_NAME} }
	redirfd -w 1 /run/cgroup2/containers/${CONTAINER_USER}/${CONTAINER_NAME}/cgroup.procs
	printf "%s" ${NS_PID}
}

if { touch ${CONTAINER_TMPFS}.lockfile }
s6-setlock -n ${CONTAINER_TMPFS}.lockfile

# Needs to exists otherwise the find below fails.
if { mkdir -p ${CONTAINER_TMPFS} }
# This is non-POSIX but even busybox has these flags.
if { find ${CONTAINER_TMPFS} -depth -mindepth 2 -delete }
#if { rm -rf ${CONTAINER_TMPFS} }

if { mkdir -p ${CONTAINER_TMPFS}/${tmpfs_dirs} }
if { chmod 1770 ${CONTAINER_TMPFS}/${tmpfs_dirs} }
if { chown root:${CONTAINER_USER} ${CONTAINER_TMPFS}/${tmpfs_dirs} }
if { mount -a --fstab data/fstab }

# Put UID/GID/GIDLIST into environment for use by s6-applyuidgid below
s6-envuidgid ${CONTAINER_USER}

env
  HOST=${CONTAINER_NAME}
#  NS_EXTRA="if { mount -o bind,ro /etc/passwd etc/passwd } if { mount -o bind,ro /etc/group etc/group }"

emptyenv -c
export NS_NO_PID1 1
pidns_run
ns_run data/root
/mnt/ns/bin/s6-applyuidgid -U
$@