#!/usr/bin/env bash
# gclip -- get text into clipboard
# pclip -- put/paste text from clipboard
# psel -- put/paste text from primary selection
#
# (The names are a little backwards, but that's how the UnxUtils gclip.exe worked.)

. lib.bash || exit

case ${0##*/} in
	gclip)
		if [ "$WAYLAND_DISPLAY" ] && have wl-copy; then
			cmd="wl-copy -t 'text/plain;charset=utf-8'"
		elif [ "$DISPLAY" ] && have xsel; then
			cmd="xsel -i -b -l /dev/null"
		elif [ "$DISPLAY" ] && have xclip; then
			cmd="xclip -in -selection clipboard"
		elif [ "$WAYLAND_DISPLAY" ] || [ "$DISPLAY" ]; then
			vdie "no clipboard tools installed"
		else
			vdie "clipboard not available"
		fi;;

	pclip)
		if [ "$WAYLAND_DISPLAY" ] && have wl-paste; then
			cmd="wl-paste -t 'text/plain;charset=utf-8'"
		elif [ "$DISPLAY" ] && have xsel; then
			cmd="xsel -o -b"
		elif [ "$DISPLAY" ] && have xclip; then
			cmd="xclip -out -selection clipboard"
		elif [ "$WAYLAND_DISPLAY" ] || [ "$DISPLAY" ]; then
			vdie "no clipboard tools installed"
		else
			vdie "clipboard not available"
		fi;;

	psel)
		if [ "$WAYLAND_DISPLAY" ] && have wl-paste; then
			cmd="wl-paste -p -t 'text/plain;charset=utf-8'"
		elif [ "$DISPLAY" ] && have xsel; then
			cmd="xsel -o -p"
		elif [ "$DISPLAY" ] && have xclip; then
			cmd="xclip -out -selection primary"
		elif [ "$WAYLAND_DISPLAY" ] || [ "$DISPLAY" ]; then
			vdie "no clipboard tools installed"
		else
			vdie "clipboard not available"
		fi;;

	*)
		vmsg "bad invocation" >&2
		exit 2;;
esac

if [ "$1" = -q ]; then
	echo "$cmd"
else
	eval "$cmd"
fi
