#!/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 from within the source directory of
#  the web site. Set $EDITOR environment variable to select a text editor.

# Last edited: 2021-12-05

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.
#  echo "$1" | sed 's@+@ @g;s@%@\\x@g' | tr -d '\000' | 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
}
#[[ -f "$entry" ]] && editentry "/$entry"					# Don't check in the CWD directly to make sure it is actually the entries directory.
#[[ -f "entries/$entry" ]] && editentry "entries/$entry"
#[[ -f "../entries/$entry" ]] && editentry "../entries/$entry"
#[[ -f "../../entries/$entry" ]] && editentry "../../entries/$entry"
#[[ -f "../../../entries/$entry" ]] && editentry "../../../entries/$entry"
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.
