#!/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}.${CONTAINER_USER}
#	define CONTAINER_DATA /mnt/volumes/containers/user/${CONTAINER_USER}/${CONTAINER_NAME}
	define -s tmpfs_dirs "home run tmp inbox run/inbox tmp/.X11-unix"
	importas -D ns -s -C -u CONTAINER_MNT_DIRS CONTAINER_MNT_DIRS
}

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 { rm -rf ${CONTAINER_TMPFS} }
if { mkdir -p ${CONTAINER_TMPFS}/${tmpfs_dirs} ${CONTAINER_TMPFS}/mnt/${CONTAINER_MNT_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 setup script (optional)
if {
	ifelse { s6-test -x ${CONTAINER_USER_HOME}/container-setup } {
		env HOME=${CONTAINER_USER_HOME} USER=${CONTAINER_USER}
		s6-applyuidgid -U
		${CONTAINER_USER_HOME}/container-setup ${CONTAINER_TMPFS} ${CONTAINER_NAME}
	}
}

#multisubstitute { importas -i UID UID importas -i GID GID }
env
  HOST=${CONTAINER_NAME}
  #RUN_CHOWN=${UID}:${GID}
  NS_EXTRA="if { mount -o bind,ro /dev/snd dev/snd } if { mount -o bind,ro /etc/passwd etc/passwd } if { mount -o bind,ro /etc/group etc/group }"

unshare -n  # make new network namespace
if { ip addr add 127.0.0.1/8 dev lo }
if { ip addr add ::1/128 dev lo }
if { ip link set lo up }
# Put UID/GID/GIDLIST into environment for use by s6-applyuidgid below
emptyenv -c
ns_run data/root
/mnt/ns/bin/s6-applyuidgid -U
env HOME=${CONTAINER_USER_HOME} USER=${CONTAINER_USER}
${CONTAINER_USER_HOME}/run/init