#!/bin/sh -e

os=$(uname -s)

if [ "${os}" = "Darwin" ]; then

  copy() {
    reattach-to-user-namespace pbcopy
  }
  paste() {
    reattach-to-user-namespace pbpaste
  }

elif [ -n "${WAYLAND_DISPLAY:-}" ]; then

  copy() {
    wl-copy
  }
  paste() {
    wl-paste
  }

elif [ -n "${DISPLAY:-}" ]; then

  selection=clipboard
  #selection=primary
  copy() {
    xclip -in -selection "${selection}"
  }
  paste() {
    xclip -out -selection "${selection}"
  }

else

  # use terminal escape sequence to set clipboard
  copy() {
    cb="$(base64)"
    printf '\e]52;%s;%s\a' pc "${cb}"
  }
  paste() {
    echo "Paste not supported in current environment" >&2
    exit 1
  }

fi

if [ "$#" -eq 0 ]; then
  # if STDIN is not the terminal
  [ ! -t 0 ] && do_copy=y

  # if STDOUT is not the terminal, or nothing else was done
  [ ! -t 1 ] || [ -t 0 ] && do_paste=y
else
  # command line args
  for arg in "$@"; do
    case "x${arg}" in
      xin | x-in | xcopy | x-copy)
        do_copy=y
        ;;
      xout | x-out | xpaste | x-paste)
        do_paste=y
        ;;
      *)
        exit 0
        ;;
    esac
  done
fi

# main
# copy first, then paste so that data will flow through
if [ "${do_copy}" = y ]; then
  copy
fi
if [ "${do_paste}" = y ]; then
  paste
fi
