#!/usr/bin/env bash
#
# henious edit of an osc52 clipboard script by samoshkin
#
#                              ██
#   ██   ██                   ░██
#  ░░██ ██   ██████   ███████ ░██  ██
#   ░░███   ░░░░░░██ ░░██░░░██░██ ██
#    ░██     ███████  ░██  ░██░████
#    ██     ██░░░░██  ░██  ░██░██░██
#   ██     ░░████████ ███  ░██░██░░██
#  ░░       ░░░░░░░░ ░░░   ░░ ░░  ░░
#
# see: 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)
# see: https://code.x-e.ro/dotfiles

set -eu
# check extglob support in a subshell, disregard if unsupported
# shellcheck disable=SC3044
(shopt -s extglob 2>/dev/null) && shopt -s extglob

# get data either from stdin or from a file
buf=$(cat -- "$@")

# check for local clipboards
copy_backend=""
# shellcheck disable=SC2312
if command -v pbcopy >/dev/null 2>&1; then
  copy_backend="pbcopy"
elif command -v reattach-to-user-namespace >/dev/null 2>&1; then
  copy_backend="reattach-to-user-namespace pbcopy"
elif [ -n "${WAYLAND_DISPLAY-}" ] && command -v wl-copy >/dev/null 2>&1; then
  copy_backend="WAYLAND_DISPLAY=wayland-0 wl-copy --trim-newline"
elif command -v wl-copy >/dev/null 2>&1; then
  copy_backend="WAYLAND_DISPLAY=wayland-0 wl-copy --trim-newline"
elif [ -n "${DISPLAY-}" ] && command -v xsel >/dev/null 2>&1; then
  copy_backend="xsel -i"
elif [ -n "${DISPLAY-}" ] && command -v xclip >/dev/null 2>&1; 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
# see: https://sunaku.github.io/tmux-yank-osc52.html
# see: https://github.com/sunaku/home/blob/master/bin/yank
#
# The maximum length of an OSC 52 escape sequence is 100_000 bytes, of which
# 7 bytes are occupied by a "\033]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="\033]52;c;$(printf '%b' "${buf}" | head -c "${maxlen}" | base64 | tr -d '\r\n')\a"

# multiplexin? update the eascape sequence
if [ -n "${TMUX-}" ] && (tmux has-session 2>/dev/null); then
  esc="\033Ptmux;\033${esc}\033\\"
  # 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
