#!/bin/sh

# shellcheck disable=SC2250

usage() {
  echo "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 Neovim.
- 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.
"
}

[ -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" && nvim "$mdfile"
}

fzffind() {
  default='enter:become(nvim {})'
  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)'
  glow='ctrl-g:become(glow {})'
  html='ctrl-h:become(open-in-browser {})'

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

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

fzfcombined() {
  setsharedvars
  or_regex="$(echo $* | tr ' ' '|')"
  and_regex=""
  for part in "$@"; do and_regex="${and_regex}(?=.*$part)"; done
  (
    fd -etid -emd . | rg --pcre2 "$and_regex" | sed 's|^\./||' | sed 's/$/:1/'
    rg --line-number --no-heading --color=always --smart-case \
      --glob '*.{tid,md}' "$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 ;;
  find)
    shift
    cd "$WIKI_DIR" && fd -e tid -e md --exclude '$__*' "$*"
    ;;
  "") cd "$WIKI_DIR" && fzffind "$@" ;;
  ifind)
    shift
    cd "$WIKI_DIR" && fzffind "$@"
    ;;
  grep)
    shift
    cd "$WIKI_DIR" && rg -g '*.{tid,md}' "$@"
    ;;
  igrep)
    shift
    cd "$WIKI_DIR" && fzfgrep "$@"
    ;;
  *) cd "$WIKI_DIR" && fzfcombined "$@" ;;
esac
