#!/command/execlineb -P
fdmove -c 2 1

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
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}

# Run user's script to populate /home /run and/or /tmp
if {
	env HOME=${CONTAINER_USER_HOME}
	s6-applyuidgid -U
	backtick -E CONTAINER_ROOT { s6-linkname data/root }
	confz container_sysroot_rundir
		container_root=${CONTAINER_ROOT}
		container_name=${CONTAINER_NAME}
		tmp_dir=${CONTAINER_TMPFS}
}

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

emptyenv -c
ns_run data/root
/mnt/ns/bin/s6-applyuidgid -U
env HOME=/root
/run/init