#!/bin/sh -e

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

  while [ $# -gt 0 ]; do
    # shellcheck disable=SC2249
    case "$1" 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=""

  # while getopts f:lm:s:t: name; do
  while [ $# -gt 0 ]; do
    # shellcheck disable=SC2249
    case "$1" 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
