#!/bin/sh
# yank - copy input to tmux buffer and system clipboard via OSC 52
# Usage: yank < file
#        ... | yank

buf=$(cat)
[ -z "$buf" ] && exit 0

if [ -n "$TMUX" ]; then
  # Use load-buffer -w to set the tmux paste buffer AND send OSC 52 to the
  # terminal. By default it targets the current client, but in popup sessions
  # (e.g. tmux display-popup running a nested tmux session), the current
  # client is the popup — which can't forward OSC 52 to the real terminal.
  # So we find the real terminal client and target it explicitly with -t.
  #
  # How: the real terminal client (terminal -> shell -> tmux) was started
  # outside tmux, so the tmux server PID is NOT in its ancestry. Clients
  # started from within tmux (e.g. neovim :terminal -> tmux new-session) ARE
  # descendants of the server. Walk each client's parent PID chain to tell
  # them apart.
  # tmux server PID
  server_pid=$(tmux display-message -p '#{pid}')
  # For each client, walk its parent PID chain to find one not spawned from tmux.
  #   e.g. "12345 /dev/ttys038\n67890 /dev/pts/0\n..."
  tty=$(tmux list-clients -F '#{client_pid} #{client_tty}' | while read -r cpid ctty; do
    pid=$cpid
    nested=0
    # walk towards PID 1 (init)
    while [ "$pid" -gt 1 ] 2>/dev/null; do
      # get parent PID
      ppid=$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ')
      # process gone
      [ -z "$ppid" ] && break
      if [ "$ppid" = "$server_pid" ]; then
        # spawned from within tmux, its tty is a pane pty
        nested=1
        break
      fi
      # move up one level
      pid=$ppid
    done
    if [ "$nested" = 0 ]; then
      # found the real terminal
      printf '%s' "$ctty"
      break
    fi
  done)
  # -w sets the tmux buffer AND sends OSC 52 to the target client.
  # This handles popup sessions but may not work over SSH.
  if [ -n "$tty" ]; then
    printf '%s' "$buf" | tmux load-buffer -w -t "$tty" -
  else
    # fallback to current client
    printf '%s' "$buf" | tmux load-buffer -w -
  fi
fi

# Also write OSC 52 directly to /dev/tty. Over SSH this is what actually
# reaches the local terminal (load-buffer -w doesn't). In popup sessions
# this may be blocked, but load-buffer -w -t above covers that case.
b64=$(printf '%s' "$buf" | base64 | tr -d '\n')
printf '\033]52;c;%s\a' "$b64" >/dev/tty 2>/dev/null
