bin/.local/bin/yank
#!/bin/bash
# ██
# ██ ██ ░██
# ░░██ ██ ██████ ███████ ░██ ██
# ░░███ ░░░░░░██ ░░██░░░██░██ ██
# ░██ ███████ ░██ ░██░████
# ██ ██░░░░██ ░██ ░██░██░██
# ██ ░░████████ ███ ░██░██░░██
# ░░ ░░░░░░░░ ░░░ ░░ ░░ ░░
#
# henious edit of an osc52 clipboard script by samoshkin
# https://github.com/samoshkin/tmux-config/blob/master/tmux/yank.sh
# this version tries to push to every clipboard it possible can xD
# cc0 mmxxiii xero (https://x-e.ro | https://git.io/.files)
set -eu
shopt -s extglob
# get data either from stdin or from a file
buf=$(cat -- "$@")
# bin test
installed() {
type "" &>/dev/null
}
# check for local clipboards
copy_backend=""
if installed pbcopy; then
copy_backend="pbcopy"
elif installed reattach-to-user-namespace; then
copy_backend="reattach-to-user-namespace pbcopy"
elif [ -n "${DISPLAY-}" ] && installed xsel; then
copy_backend="xsel -i"
elif [ -n "${DISPLAY-}" ] && installed xclip; then
copy_backend="xclip -i -f -selection primary | xclip -i -selection clipboard"
elif [ -n "${copy_backend_remote_tunnel_port-}" ] && [ "$(ss -n -4 state listening "( sport = $copy_backend_remote_tunnel_port )" | tail -n +2 | wc -l)" -eq 1 ]; then
copy_backend="nc localhost $copy_backend_remote_tunnel_port"
fi
# if copy backend is resolved, copy to local clipboard
[ -n "$copy_backend" ] && printf "%b" "$buf" | eval "$copy_backend"
# copy via OSC 52 ANSI escape sequence to controlling terminal
# https://sunaku.github.io/tmux-yank-osc52.html
# The maximum length of an OSC 52 escape sequence is 100_000 bytes, of which
# 7 bytes are occupied by a "3]52;c;" header, 1 byte by a "\a" footer, and
# 99_992 bytes by the base64-encoded result of 74_994 bytes of copyable text
maxlen=74994
buflen=$(printf %s "$buf" | wc -c)
# warn if exceeds max
if [ "$buflen" -gt "$maxlen" ]; then
printf "input is %d bytes too long, rip" "$((buflen - maxlen))" >&2
fi
# build OSC 52 ANSI escape sequence
esc="3]52;c;$(printf "%b" "$buf" | head -c $maxlen | base64 | tr -d '\r\n')\a"
# sent directly to the ssh tty (requires root?)
[ -n "$SSH_TTY" ] && (printf "%b" "$esc" > "$SSH_TTY") &>/dev/null
# multiplexin? update the eascape sequence
if (tmux has-session 2>/dev/null); then
esc="3Ptmux;3$esc3\"
# send to all terminals \o/
for pts in /dev/pts/[0-9]; do
printf "%b" "$esc" >"$pts"
done
else
# print that shiz raw
printf "%b" "$esc"
fi