#!/bin/sh
#
# ---
# see: https://github.com/MaxGyver83/dotfiles/blob/master/scripts/bin/wiki

usage() {
  cat <<EOF
Usage:
  wiki new [FILENAME]
  wiki list
  wiki [i]find FILENAME_PART
  wiki [i]grep PATTERN ...
  wiki FILENAME_PART|PATTERN

  new: Pass FILENAME without path and file extension.
  ifind/igrep: Interactive search using fzf.

Key bindings in FZF:

  - Enter: Open in [Neo]vim.
  - Ctrl-f: Print filename.
  - Ctrl-b: Open in bat.
  - Ctrl-l: Open selected line in bat.
  - Ctrl-r: Open in rich.
  - Ctrl-g: Open in glow.
  - Ctrl-h: Convert to HTML and open in browser.
EOF
}

[ -n "${NOUS-}" ] && WIKI_DIR="${NOUS-}"

[ -z "${WIKI_DIR}" ] \
  && printf '%s\n' "Set/export ${WIKI_DIR} before running this script!" \
  && exit 1
[ ! -d "${WIKI_DIR}" ] \
  && printf '%s\n' "Can't find directory '${WIKI_DIR}'!" \
  && exit 1

new() {
  if [ -n "$1" ]; then
    name="$*"
    echo "Title: ${name}"
  else
    # switch to bash for `read -e` (=readline)?
    # or use:
    # $EDITOR /tmp/title && name="$(head -n1 /tmp/title)"
    read -r -p "Title: " name
    # remove trailing newline
    name="${name%
}"
  fi
  # replace colons and slashes with underscores
  mdfile="${WIKI_DIR}/$(echo "${name}" | tr ':/' _).md"

  now="$(date -u '+%Y%m%d%H%M%S%3N')"
  printf '%s' "\
created: ${now}
modified: ${now}
tags:
title: ${name}
type: text/x-markdown" >"${mdfile}".meta

  touch "${mdfile}" && ${EDITOR:-vi} "${mdfile}"
}

fzffind() {
  default="enter:become(${EDITOR:-vi} {})"
  filename="ctrl-f:become(echo '${WIKI_DIR}'/{})"
  bat='ctrl-b:become(bat --style=plain,header-filename -l md {})'
  # rich='ctrl-r:become(python -m rich.markdown -c {} |& less -R)'
  rich='ctrl-r:become(less {})'
  glow='ctrl-g:become(glow {} 2>/dev/null || readme {} 2>/dev/null)'
  html='ctrl-h:become(browser {})'

  preview='bat -l=md --style=numbers --color=always {1}'

  # shellcheck disable=SC2016,SC2250
  fd -e tid -e md -e txt -e org --exclude '$__*' "$*" -X ls -t | sed 's|^\./||' \
    | fzf -d ':' --exit-0 --bind "$default,$bat,$rich,$glow,$filename,$html" \
      --preview-window 'down:40%:+{2}' \
      --preview "$preview"
}

setsharedvars() {
  default='enter:become(open-in-nvim {})'
  filename="ctrl-f:become[echo {} | cut -d: -f1 | (printf '%s' '${WIKI_DIR}'/ && cat)]"
  line='ctrl-l:become(open-in-bat {} single-line)'
  bat='ctrl-b:become(open-in-bat {})'
  rich='ctrl-r:become(open-in-rich {})'
  glow='ctrl-g:become(open-in-glow {})'
  html='ctrl-h:become(open-in-browser {})'
  # Alternative to external open-in-browser script (and open-in-*):
  # Use bash; define and export open-in-browser function.

  preview='bat -l=md --style=numbers --color=always --highlight-line {2} {1}'
}

fzfgrep() {
  # search for empty string if no arguments given
  [ -z "$1" ] && set -- ''
  setsharedvars
  # shellcheck disable=SC2250
  rg --line-number --no-heading --color=always --smart-case \
    --glob '*.{tid,md,txt,org}' "${@}" \
    | fzf -d ':' --ansi --no-sort --exit-0 \
      --bind "$default,$bat,$rich,$glow,$filename,$line,$html" \
      --preview-window 'down:40%:+{2}' \
      --preview "$preview"
}

# shellcheck disable=SC2250
fzfcombined() {
  setsharedvars
  or_regex="$(echo $* | tr ' ' '|')"
  and_regex=""
  for part in "$@"; do
    and_regex="${and_regex}(?=.*$part)"
  done
  (
    fd -etid -emd -etxt -eorg . | pcre2grep "$and_regex" | sed 's|^\./||' | sed 's/$/:1/'
    rg --line-number --no-heading --color=always --smart-case \
      --glob '*.{tid,md,txt,org}' "$or_regex"
  ) \
    | fzf -d ':' --ansi --no-sort --exit-0 \
      --bind "$default,$bat,$rich,$glow,$filename,$line,$html" \
      --preview-window 'down:40%:+{2}' \
      --preview "$preview"
}

case "$1" in
  -h | --help) usage ;;
  new)
    shift
    new "$@"
    ;;
  list)
    cd "${WIKI_DIR}" && fd -etid -emd -etxt -eorg
    ;;
  find)
    shift
    # shellcheck disable=SC2016
    cd "${WIKI_DIR}" && fd -e tid -e md -e txt -e org --exclude '$__*' "$*"
    ;;
  "")
    cd "${WIKI_DIR}" && fzffind "$@"
    ;;
  ifind)
    shift
    cd "${WIKI_DIR}" && fzffind "$@"
    ;;
  grep)
    shift
    cd "${WIKI_DIR}" && rg -g '*.{tid,md,txt,org}' "$@"
    ;;
  igrep)
    shift
    cd "${WIKI_DIR}" && fzfgrep "$@"
    ;;
  *)
    cd "${WIKI_DIR}" && fzfcombined "$@"
    ;;
esac
