#!/bin/zsh
# vim: sts=2 sw=2 et
setopt no_unset warn_create_global

main() {
  local container display xsession_cookie
  (( $# == 2 )) || exit 100
  container=$1
  xsvc_name=$2
  [[ $container == */* ]] && exit 100
  display=${DISPLAY#:}
  xsession_cookie=${"$(xauth list $DISPLAY)"##* } || exit $?

  s6-sudo /run/cmd.s link $container xsession.$display.$USER run/exec/xsvc run/exec/exec || exit $?
  s6-sudo /run/cmd.s link xpra.$USER xsession.$display.$USER run/exec/x11 || exit $?
  s6-sudo /run/cmd.s link xsession.$display.$USER xpra.$USER tmp/.X11-unix/X$display || exit $?

  local -a xpra
  xpra=( $(s6-sudo /run/inbox/xpra.ccx/run/exec/x11 $display $xsession_cookie start-xpra-for-container $container) )
  (($#xpra == 2)) || exit 1

  s6-sudo /run/cmd.s link xpra.$USER $container tmp/.X11-unix/X$xpra[1] || exit $?
  exec s6-sudo /run/inbox/$container/run/exec/xsvc "$xpra[@]" "$xsvc_name"
}
typeset -f -t main

main "$@"