#!/bin/zsh
umask 077
while sleep 1; do
	prev_clipboard=$clipboard
	prev_buffer=$buffer
	clipboard="$(xclip -o -selection clipboard)"
	buffer="$(tmux save-buffer -)"
	if [[ $clipboard != $buffer ]]; then
		if [[ $prev_clipboard != $clipboard ]]; then
			#echo 'clipboard -> tmux'
			printf '%s' $clipboard | tmux load-buffer - 
		elif [[ $prev_buffer != $buffer ]]; then
			#echo 'tmux -> clipboard'
			printf '%s' $buffer | xclip -i -selection clipboard
			printf '%s' $buffer | xclip -i -selection primary
		fi
	fi
done