#! /bin/bash

############################################################################################
#
# genentry - Script to generate a new entry source file for SBWG from v0.8 onwards
# Version: 0.2.1
# Last edited: 2020-04-02
#
############################################################################################

if [ $# -eq 0 ]; then
  echo
  echo "This script creates a template for a entry source file for SBWG."
  echo
  echo "Expected title of blog entry as argument(s). The title does not have to be escaped."
  echo
  echo "A file with a name corrosponding to the title will be written to the current working"
  echo "directory immediately. Then a text editor is opened."
  echo
  echo "Examples:"
  echo "$0 \"An Exciting New Blog Post\""
  echo "$0 My Views On Presidential Pets"
  echo
  exit
fi

title="${@}"
# Choose a file name that corrosponds to the title but excludes spaces and speacial characters
#   according to my personal preferences.
filename=$(echo "${title}"|sed -e 's: :_:g'|tr -d '.!\"§$%&()[]{}?´`#\\/:*?"<>|[:space:]')

[ -f "${filename:=$(date +%Y-%m-%d_%H-%M-%S_%N)}" ] \
  && { echo "A file with the name '${filename}' already exists. No, I'm not going to overwrite it."; exit 1; }

{
  echo "note:Source file generated by "$(basename "${BASH_SOURCE[0]}")	# Inform future source readers of this irrelevant fact.
  echo "title:${@}"						# Include title tag with arguments unchecked.
  echo "created:$(date -I)"					# Created date is the current date. Other sorting conventions could be chosen, but weren't.
  echo "${SBWG_AUTHOR:+author:$SBWG_AUTHOR}"			# Include author tag if environment variable exists, leave empty line otherwise.
  echo								# Another empty line.
  echo "<p></p>"						# Start a new paragraph.
} > "${filename}" || exit 1					# End here if the file can not be written.

echo "Created file '${filename}'."				# Print file name to stdout just for info where stuff has been placed.

#"${EDITOR:-nano} -u +6,4 ${filename}"
								# I prefer nano and nobody else uses this script.
nano -u +6,4 "${filename}"					# Place the curser in the new paragraph.
