#!/bin/zsh
setopt no_unset extended_glob warn_create_global

typeset -g -A container_exec_linked
c_exec() {
	local container=$1 display=${DISPLAY#:}
	shift
	if ! (( $+container_exec_linked[$container] )); then
		s6-sudo /run/cmd.s link $container xsession.$display.$USER run/exec/exec || exit $?
		container_exec_linked[$container]=1
	fi
	s6-sudo /run/inbox/$container/run/exec/exec "$@"
}

load_wininfo() {
	local line
	local -a l
	i3windowlist | while IFS= read -r line; do
		l=( "${(@ps:\t:)line}" )
		(( $l[1] == $1 )) || continue
		wid=$l[1]
		typeset -g w_host w_class w_instance w_title term_container term_pts
		w_host=${(Q)l[2]}
		w_class=${(Q)l[3]}
		w_instance=${(Q)l[4]}
		w_title=${(Q)l[5]}
		return 0
	done
	return 1
}

make_paste_command() {
	if [[ $w_host == $HOST && $w_class == URxvt ]]; then
		# local urxvt
		local term_container term_pts
		if [[ $w_instance == *:/dev/pts/* ]]; then
			term_container=${${w_instance%%:/dev/pts/*}//:/.}
			term_pts=${w_instance#*:/dev/pts/}
		else
			make_paste_command_fallback
			return $?
		fi
		if [[ $w_title == *tmux::* ]]; then
			make_paste_command_container_tmux $term_container $term_pts
			return $?
		fi
	elif [[ $w_host == xpra && $w_title == *'«s=xpra c'* ]]; then
		make_paste_command_xpra
		return $?
	fi
	#return 1
	make_paste_command_fallback
	return $?
}

make_paste_command_container_tmux() {
	local term_container term_pts line n
	local -a l tmux_vars tmux_fmt
	term_container=$1
	term_pts=$2
	tmux_vars=(
		client_tty
		session_name
		window_index
		pane_id
		#client_flags
		#client_termfeatures
		#client_activity
		#client_created
		#client_readonly
	)
	tmux_fmt=( "#{"$^tmux_vars"}" )
	c_exec $term_container tmux list-clients -F ${(pj:\t:)tmux_fmt} | \
	while IFS= read line; do
		l=( "${(@ps:\t:)line}" )
		local -A info=( )
		for n in {1..$#tmux_vars}; do
			info[$tmux_vars[$n]]=$l[$n]
		done
		[[ $info[client_tty] == /dev/pts/$term_pts ]] || continue
		# TODO
		local -a el=(
			'multisubstitute {'
			'  importas -i container_name container_name'
			'  importas -i pane_id pane_id'
			'}'
			's6-sudo /run/inbox/${container_name}/run/exec/exec'
			'tmux load-buffer -b shiftinsert - ; paste-buffer -p -b shiftinsert -t $pane_id'
		)
		typeset -ga paste_command
		paste_command=(
			env container_name=$term_container pane_id=$info[pane_id]
			execlineb -c "${(@F)el}"
		)
		return 0
	done
	return 1
}

make_paste_command_xpra() {
	local x=
	local -A xpra_info=( )
	for x in "${(@s: :)${w_title##*«s=xpra }}"; do
		[[ $x == ?=* ]] || die "Malformed xpra info: ${(qqq)x}"
		xpra_info[${x%%=*}]=${x#?=}
	done
	local -a el=(
		'multisubstitute {'
		'  importas -i wid wid'
		'  importas -i xpra_w xpra_w'
		'  importas -i xpra_d xpra_d'
		'}'
		'if {'
		'  s6-sudo /run/inbox/xpra.ccx/run/exec/exec'
		'  in-xpra $xpra_d'
		'  xclip -i -sel CLIPBOARD'
		'}'
		'xdotool windowfocus $wid key --clearmodifiers --window $wid Shift+Insert'
	)
	typeset -ga paste_command
	paste_command=(
		env xpra_d=${xpra_info[d]} xpra_w=${xpra_info[w]} wid=$wid
		execlineb -c "${(@F)el}"
	)
}

make_paste_command_fallback() {
	local -a el=(
		'importas -i wid wid'
		'if { xclip -i }'
		'xdotool windowfocus $wid key --clearmodifiers --window $wid Shift+Insert'
	)
	typeset -ga paste_command
	paste_command=(
		env wid=$wid
		execlineb -c "${(@F)el}"
	)
}

main() {
	local wid clip
	wid=$(xdotool getactivewindow) || exit $?
	load_wininfo $wid || exit $?
	make_paste_command || exit $?
	clip | IFS= read -r -d '' clip
	[[ -n $clip ]] || exit 1
	printf '%s' $clip | "$paste_command[@]"
}
typeset -f -t main

main "$@"
exit $?
# old code

set -x
wid=$(xdotool getactivewindow) || exit $?
title=$(xdotool getwindowname $wid) || exit $?
if [[ $title != *«s=xpra\ * ]]; then
	echo >&2 "failed to determine xpra window"
	exit 3
fi
typeset -gA win_meta
for kv in ${=${title##*«s=xpra\ }}; do
	[[ $kv != *=* ]] && exit 3
	win_meta[${kv%%=*}]=${kv#*=}
done
[[ -n $win_meta[w] && -n $win_meta[d] ]] || exit 3 

#s6-sudo /run/inbox/xpra.ccx/run/exec/exec export DISPLAY $win_meta[d] xdotool getwindowname $win_meta[w]
s6-sudo /run/inbox/xpra.ccx/run/exec/exec in-xpra $win_meta[d] wmctrl -l

clip | IFS= read -r -d '' clip
[[ -n $clip ]] || exit $?
s6-sudo /run/inbox/xpra.ccx/run/exec/exec in-xpra $win_meta[d] xclip -i -sel CLIPBOARD <<<$clip || exit $?
xdotool windowfocus $wid key --clearmodifiers --window $wid 'Shift+Insert'