#!/bin/zsh
setopt no_unset extended_glob warn_create_global

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

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

	#s6-sudo /run/cmd.s up $container || 
	#	die "Failed to start container ${(qqq)container}"

	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."

	s6-sudo /run/cmd.s link xsession.$display.$USER $container run/exec/urxvt ||
		die "Failed to link urxvt socket."

	local -a el_env=(
		EXEC_PATH=$sock
		URXVT_PATH=/run/inbox/xsession.$display.$USER/run/exec/urxvt
	)
	local -a el_cmd=(
		'multisubstitute {'
		'  importas -i -u EXEC_PATH EXEC_PATH'
		'  importas -i -u URXVT_PATH URXVT_PATH'
		'}'
		's6-sudo $EXEC_PATH'
		'/mnt/ns/bin/spawn-pty rxvt-unicode-256color {'
		"  $cmd"
		'} s6-sudo $URXVT_PATH '${(qqq)${container//./:}}
	)
	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

#	if [[ -S $sock ]]; then
#		#exec s6-sudo $sock "$@"
		direct-urxvt $container "${(j: :)quoted}"
#	else
#		powerbox-plumb "container-urxvt/$container/${(j: :)quoted}"
#	fi
	
}
typeset -f -t main

main "$@"