#!/bin/zsh
setopt no_unset extended_glob warn_create_global

die() {
	printf >&2 '%s\n' "$@"
	exit 1
}

direct-urxvt() {
	local container cmd sock display
	container=$1
	cmd=$2
	sock=/run/inbox/$container/run/exec/exec 
	display=${DISPLAY#:}

	s6-sudo /run/cmd.s link $container xsession.$display.$USER run/exec/exec ||
		die "Failed to link ${(qqq)container} exec socket."

	[[ -S $sock ]] ||
		die "Failed to link ${(qqq)container} exec socket."

	local -a el_env=(
		EXEC_PATH=$sock
		TERM_NAME=${container//./:}
	)
	local -a el_cmd=(
		'multisubstitute {'
		'  importas -i -u EXEC_PATH EXEC_PATH'
		'  importas -i -u TERM_NAME TERM_NAME'
		'}'
		'/mnt/ns/bin/socketpair 3 1'
		'background -d {'
		'  fdclose 3'
		'  s6-sudo $EXEC_PATH'
		'  /mnt/ns/bin/spawn-pty rxvt-unicode-256color {'
		"    $cmd"
		'  } /mnt/ns/bin/fdsend 1 0 true'
		'}'
		'fdmove -c 1 2'
		'/mnt/ns/bin/fdrecvto 3 4'
		'fdclose 3'
		'backtick -E PTS_NAME { /mnt/ns/bin/ptsname 4 }'
		'urxvt -name ${TERM_NAME}:${PTS_NAME} -pty-fd 4'
	)
	exec env $el_env execlineb -c "${(F)el_cmd}"
}

main() {
	local container sock arg
	local -a quoted
	[[ $1 == */* ]] && die "Invalid container name: ${(qqq)1}"
	container=$1
	shift 1 || exit $?
	sock=/run/inbox/$container/run/exec/exec 

	for arg in "$@"; do
		quoted+=( "$(s6-quote -- "$arg")" )
	done

	direct-urxvt $container "${(j: :)quoted}"
	
}
typeset -f -t main

main "$@"