#!/bin/sh

set -eu

app="$(basename "$0")"
workdir="${XDG_STATE_HOME:-${HOME}/.local/state}/wl-clipboard-manager"
mkdir -p "${workdir}"
cd "${workdir}" || return

query() {
  echo "$@" | sqlite3 -line "history.db"
}

if [ ! -f "history.db" ]; then
  query "
      CREATE TABLE entries (
          id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
          timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
          contents BLOB NOT NULL UNIQUE,
          mime TEXT NOT NULL
      );
      CREATE TRIGGER cleanup AFTER INSERT ON entries BEGIN
          DELETE FROM entries WHERE id <= (SELECT id FROM entries ORDER BY id DESC LIMIT 10000, 1);
      END;
  "
fi

list_entries() {
    python -u <<-EOF
import sqlite3
for row in sqlite3.connect("history.db").cursor().execute("SELECT id, mime, contents FROM entries ORDER BY id DESC"):
    print(row[0], '| ', end='')
    if row[1] == "application/json" or row[1].startswith("text/"):
        print(row[2].decode("utf-8", errors="ignore"), end='')
    else:
        print(row[1], end='')
    print('\0', end='')
EOF
}

subcommand="${1:-dmenu}"
shift

# shellcheck disable=SC2312

case "${subcommand}" in
  daemon) wl-paste -w "$0" on-copy ;;
  lock) touch .lock ;;
  unlock) rm -f .lock ;;

  on-copy)
      [ -f .lock ] && exit 0

      file="$(mktemp)"
      trap 'rm $file' EXIT
      cat > "${file}"

      [ -n "$(find "${file}" -type f -size 0)" ] && exit 0
      [ -n "$(find "${file}" -type f -size +10000000c)" ] && exit 0

      mime="$(file --brief --mime-type "${file}")"
      # if [ "${mime}" = "application/json" ] || [ "${mime}" = text/* ]; then
      if [ "${mime}" = "application/json" ] || echo "${mime}" | grep -q 'text/*'; then
          sed -i -Ez 's/\s+$//' "${file}"
      fi

      query "INSERT OR REPLACE INTO entries (mime, contents) VALUES ('${mime}', readfile('${file}'))"
      ;;

  dmenu)
      list_entries | dmenu "$@" -0 -p clipboard -r "$(realpath "$0") preview" -f "--bind 'alt-bspace:execute-silent(wl-clipboard-manager delete {})+reload(wl-clipboard-manager list_entries)'" | {
          # shellcheck disable=SC3045
          read -r -d '' result
          [ -z "${result}" ] && exit 0

          id="${result%%\|*}"
          file="$(mktemp)"
          trap 'rm $file' EXIT

          query "SELECT writefile('${file}', contents) FROM entries WHERE id='${id}'" >/dev/null
          case "$*" in
              *overlay*) cat "${file}" ;;
              *) wl-copy < "${file}" ;;
          esac
      }
      ;;

  list-entries)
      list_entries
      ;;

  preview)
      id="${1%%\|*}"
      file="$(mktemp)"
      trap 'rm $file' EXIT

      mime="$(query "SELECT mime, writefile('${file}', contents) FROM entries WHERE id='${id}'" | awk 'NR == 1 { print $3 }')"

      # if [ "${mime}" = image/* ]; then
      if echo "${mime}" | grep -q 'image/*'; then
          kitty +kitten icat --silent < "${file}"
      else
          language="bash"
          [ "${mime}" = application/json ] && language="json"
          [ "${mime}" = text/x-c ] && language="c"
          [ "${mime}" = text/x-c++ ] && language="c++"
          [ "${mime}" = text/x-diff ] && language="diff"
          [ "${mime}" = text/x-makefile ] && language="makefile"
          [ "${mime}" = text/x-script.python ] && language="python"

          bat -l "${language}" --color always -pp < "${file}"
      fi
      ;;

  delete)
      [ -z "${1:-}" ] && echo >&2 "Usage: ${app} delete <id>" && exit 1
      id="${1%%\|*}"
      query "DELETE FROM entries WHERE id='${id}'" >/dev/null
      ;;

  *)
      echo >&2 "Usage: ${app} <daemon|lock|unlock|on-copy|dmenu|preview|delete>"
      exit 1
      ;;
esac
