#!/bin/sh
# Copy stdin to the system clipboard, regardless of platform or how deep in
# ssh/tmux this shell is: prefer a local clipboard tool for the current
# display server, and fall back to a single plain OSC 52 write when no local
# tool is available (e.g. a headless remote host). Any tmux hops in between
# here and the real terminal relay that onward themselves, recursively, via
# the pane-set-clipboard hook in tmux.conf -- this doesn't need to know or
# guess how many hops there are.
if command -v pbcopy >/dev/null 2>&1; then
    exec pbcopy
elif [ -n "$WAYLAND_DISPLAY" ] && command -v wl-copy >/dev/null 2>&1; then
    # wl-copy/xclip both hold the selection by staying alive as a background
    # process (X11/Wayland selections have no central store -- the owner has
    # to serve paste requests live). setsid -f detaches that process from
    # our session so tmux's copy-pipe job cleanup can't kill it right after.
    setsid -f wl-copy
elif [ -n "$DISPLAY" ] && command -v xclip >/dev/null 2>&1; then
    setsid -f xclip -selection clipboard
else
    data=$(base64 | tr -d '\n')
    printf '\033]52;c;%s\a' "$data" > /dev/tty
fi
