#!/bin/bash

# Edits a SBWG entry source file from the command line and automatically adds the current date as edited tag.
# Set $EDITOR environment variable to select a text editor. Compatible with SBWG versions from 0.9.17 anwards.

# Last edited: 2022-08-06

decode_url() {
  printf '%s' "$1" | sed 's@+@ @g;s@%@\\x@g' | xargs -0 printf '%b'		# If what was passed looks like a URL turn it into the corrosponding file path.
}

editentry() {
  [[ -z ${1} ]] && return 1
  sed -i "1s/^/edited:$(date --iso-8601)\n/" "$1" 				# Add the edited tag to the file, start an editor and exit this script.
  "${EDITOR:-nano}" "$1" && exit 0						# Start an editor, defaulting to nano.
  exit 0									# Exit this script so that no further file paths are checked.
}

entry=$(basename -s .html "$(decode_url $@)")

[[ ${entry} ]] || {
  printf 'You must enter an entry name or the URL of an entry.\n'
  exit 1
}

file="$(find . -name "${entry}" -print0 -quit 2> /dev/null)"

editentry "${file}" || {
                         printf 'I do not see that entry here. Are you are '
                         printf 'in the right SBWG source directory?\n'
                         exit 1
                       }							# If this line was reached, it seems that none of the files exist.

cdir="$(find . -type d -name cache -print0 -quit 2> /dev/null)"
[[ ${cdir} ]] || cdir="$(find .. -type d -name cache -print0 -quit 2> /dev/null)" \
[[ ${cdir} ]] || cdir="$(find ../.. -type d -name cache -print0 -quit 2> /dev/null)" \
[[ ${cdir} ]] || cdir="$(find ../../.. -type d -name cache -print0 -quit 2> /dev/null)"

[[ ${cdir} ]] && rm -rf -- "${cdir}/tags/entries/**/${entry}" \
                           "${cdir}/entries/below/${entry}" \
                           "${cdir}/entries/above/${entry}" \
                           "${cdir}/entries/title/${entry}" 2> /dev/null


