#!/usr/bin/env bash

# Safer shell script with these options
# -e          : exit if a command exits with non-zero status
# -u          : exit if an expanded variable does not exist
# -o pipefail : if a command in a pipeline fail, fail the pipeline
#               (e.g this now fails: false | true)
set -euo pipefail

# Clipboard provider for the system clipboard.
# It selects the best clipboard provider based on the current environment.

if [[ -n ${SSH_TTY:-} ]]; then
  # We are under SSH, we NEED osc52 to set system's clipboard
  copy_provider=osc52
  paste_provider=none
elif [[ -d /Library ]]; then
  # We are local, this is MacOS
  copy_provider=pbmacos
  paste_provider=pbmacos
elif [[ -n ${WAYLAND_DISPLAY} ]]; then
  # We are local, this is Linux Wayland
  copy_provider=wayland
  paste_provider=wayland
elif [[ -n ${DISPLAY} ]]; then
  # We are local, this is Linux X11
  copy_provider=xclip
  paste_provider=xclip
fi

action="$1"
case "$action" in
  copy)
    cli-clipboard-provider copy-to "$copy_provider"
    ;;
  paste)
    cli-clipboard-provider paste-from "$paste_provider"
    ;;
  *)
    >&2 echo "ERROR: invalid action '$action', must be copy or paste"
    exit 1
    ;;
esac

# vim:set sw=2:
