#!/bin/sh
#
# xcp - script to copy to X11 clipboard or paste to stdout when -o is given
#
# uses xsel if available, and falls back to xclip.
# xsel is preferred because copying using xclip and pasting into certain
# textareas resulted in all newlines being stripped.
# but using xsel worked correctly.
#
# ---
# see: https://github.com/neovim/neovim/issues/5853
# source: https://github.com/BurntSushi/dotfiles

paste=
while true; do
  case "$1" in
    -o | --output)
      paste=yes
      shift
      ;;
    -h | --help)
      usage
      exit 0
      ;;
    -*)
      usage
      exit 1
      ;;
    *) break ;;
  esac
done

if cmd-exists wl-copy; then
  if [ -z "${paste}" ]; then
    wl-paste --no-newline
  else
    wl-copy --trim-newline
  fi
elif cmd-exists xsel; then
  if [ -z "${paste}" ]; then
    xsel -i --clipboard
  else
    xsel -o --clipboard
  fi
elif cmd-exists xclip; then
  if [ -z "${paste}" ]; then
    xclip -selection clipboard
  else
    xclip -o -selection clipboard
  fi
else
  echo "neither xsel (preferred) nor xclip are installed" >&2
  exit 1
fi
