#!/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.

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() {
  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 $@)")
#[[ -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"
echo "I don't see that entry here. Are you in the right directory?"		# If this line was reached, it seems that none of the files exist.
