#!/bin/bash

_wayland() {
  file=
  mode=put
  args=""

  # shellcheck disable=SC2220,SC2249
  while getopts 'f:l:m:s:t:' name; do
    case ${name} in
      f) file=${OPTARG} ;;
      l)
        args="${args}--list-targets"
        mode="get"
        ;;
      m) mode=${OPTARG} ;;
      s) [ "${OPTARG}" = "primary" ] && args="${args}--primary" ;;
      t) args="${args}--type \"${OPTARG}\"" ;;
    esac
  done

  if [ "${mode}" = "put" ]; then
    if [ -n "${file}" ]; then
      exec wl-copy "${args}" <"${file}"
    else
      exec wl-copy "${args}"
    fi
  else
    exec wl-paste "${args}"
  fi
}

_x11() {
  file=
  mode=put
  args=""

  # shellcheck disable=SC2220,SC2249
  while getopts 'f:l:m:s:t:' name; do
    case ${name} in
      f) file=${OPTARG} ;;
      l) args="${args}-t TARGETS -o" ;;
      m) [ "${OPTARG}" = "put" ] && args="${args}-i" || args="${args}-o" ;;
      s) [ "${OPTARG}" = "clipboard" ] && args="${args}-selection clipboard" ;;
      t) args="${args}-t \"${OPTARG}\"" ;;
    esac
  done

  # must be last argument.
  if [ -n "${file}" ]; then
    args="${args}\"${file}\""
  fi

  exec xclip "${args}"
}

if test -n "${WAYLAND_DISPLAY-}"; then
  _wayland "$@"
else
  _x11 "$@"
fi
