#!/bin/bash

# Script to edit a SBWG entry source file from the command line and add the current date as edited tag automatically. Only works if the current working directory is
# or is inside the source directory of the web site. Set $EDITOR environment variable to select a text editor. Compatible with SBWG versions from 0.9.17 anwards.

# Last edited: 2021-12-31

decode_url() {
  echo "$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} ]] || {
  echo "You must enter an entry name or the URL of an entry."
  exit 1
}
file="$(find . -name "${entry}" -print0 -quit 2> /dev/null)"
editentry "${file}" \
  || echo "I don't see that entry here. Are you in the right SBWG source directory?"	# If this line was reached, it seems that none of the files exist.
