#!/bin/sh
# clipboard TARGET: puts stdin on the desktop's clipboard as TARGET, since
# noVNC's clipboard carries text only. For an image pasted into the viewer it
# is image/png (PUT /api/clipboard/image); for files pasted into it,
# x-special/gnome-copied-files, the list the file manager and the desktop
# paste copies of (PUT /api/clipboard/files).
#
# xclip reads the content and forks, and the fork stays behind to hand it to
# whichever app pastes, until something else is copied. Two things about that
# fork:
#
#   - It inherits this script's stdout and stderr, and the app would wait for
#     them to close until something else is copied. So xclip writes to a file
#     instead.
#   - It takes the clipboard after the parent has exited, so the script waits
#     until the clipboard hands out this content: the viewer pastes as soon as
#     this returns, and must not get what was copied before.
#
# Exit code 3 means the desktop's display is not up yet.
: "${DISPLAY:?the app sets DISPLAY}"
target=${1:?usage: clipboard TARGET}
[ -S "/tmp/.X11-unix/X${DISPLAY#:}" ] || exit 3
dir=$(mktemp -d) || exit 1
trap 'rm -rf "$dir"' EXIT
cat >"$dir/content" || exit 1
if ! xclip -selection clipboard -target "$target" -in "$dir/content" </dev/null >/dev/null 2>"$dir/error"; then
	cat "$dir/error" >&2
	exit 1
fi
for _ in $(seq 1 60); do
	xclip -selection clipboard -target "$target" -out 2>/dev/null | cmp -s - "$dir/content" && exit 0
	sleep 0.05
done
echo "the desktop's clipboard did not take it" >&2
exit 1
