#!/bin/sh
# clipboard-image: puts the PNG on stdin on the desktop's clipboard, for an
# image pasted into the viewer (PUT /api/clipboard/image): noVNC's clipboard
# carries text only. The desktop add-on's copy of the script
# internal/docker/desktop.go runs in the desktop image.
#
# xclip reads the image 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 image: 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}"
[ -S "/tmp/.X11-unix/X${DISPLAY#:}" ] || exit 3
dir=$(mktemp -d) || exit 1
trap 'rm -rf "$dir"' EXIT
cat >"$dir/image.png" || exit 1
if ! xclip -selection clipboard -target image/png -in "$dir/image.png" </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 image/png -out 2>/dev/null | cmp -s - "$dir/image.png" && exit 0
	sleep 0.05
done
echo 'the image did not reach the clipboard' >&2
exit 1
