#!/usr/bin/env bash

# shellcheck disable=SC2312

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

# 7 bytes are occupied by a "\033]52;c;" header, 1 byte by a "\a" footer, and
# 99992 bytes by the base64-encoded result of 74994 bytes of copyable text
maxlen=74994
if [ "$(printf %s "${buf}" | wc -c 2>/dev/null)" -gt "${maxlen}" ]; then
  exit 1
fi
if [ -n "${TMUX}" ]; then
  otty=$(tmux list-panes -F '#{pane_tty}' -f '#{pane_active}')
else
  otty=${TTY:-${SSH_TTY}}
  if [ -z "${otty}" ]; then
    otty="/dev/$(ps -p "${PPID}" -o tty=)"
  fi
  if [ -z "${otty}" ]; then
    printf '%s' "${buf}"
    exit 2
  fi
fi
printf '\033]52;c;%s\a' "$(printf %s "${buf}" | head -c "${maxlen}" | base64)" >"${otty}"
