#!/bin/zsh
unset TMUX
pidof urxvtd &>/dev/null || urxvtd -q -f -o

if [[ -n "$XDG_DATA_HOME" ]]; then
	tmux_sesssion_dir=$XDG_DATA_HOME/tmux_session
else
	tmux_sesssion_dir=$HOME/.local/share/tmux_session
fi

typeset -A sessions attached

if [[ -f $tmux_sesssion_dir/$DISPLAY ]]; then
	while IFS=: read session workspace; do
		sessions[${session}]=$workspace
	done <$tmux_sesssion_dir/$DISPLAY
fi

# the "attached" flag of tmux is not reliable so we search window titles for
# session identifiers, which has the advantage of supporting multiple displays
attached=(
	$(wmctrl -l | sed -n "/tmux::[^:]*:$USER@$HOST/{ s/.*tmux::\([^:]*\):$USER@$HOST.*/\1 1/; p }")
)

if wmctrl -m | grep -q 'Name: i3'; then
	is_i3=1
else
	is_i3=0
fi

tmux list-sessions -F "#{session_name}" | \
while read session; do
	if ! (($+attached[$session])); then
		if (($+sessions[$session] && ! $is_i3)); then
			# not all windowmanagers support moving windows via wmctrl, so we
			# switch to desired workspace before spawning the terminal
			wmctrl -s $sessions[$session]
			urxvtc -name "tmux_$session" -e tmux-workspace-attach $sessions[$session] $session
			# wait until the window appears
			N=120
			while ! wmctrl -l | grep tmux::${session}:$USER@$HOST; do
				N=$(($N - 1))
				if (($N)); then sleep .01; else break; fi
			done
		else
			urxvtc -name "tmux_$session" -e tmux attach -t $session
		fi
	fi
done