#! /bin/bash

############################################################################################
#
# genentry - Generates and edits a new entry source file for SBWG v0.8 or later
# Version: 0.2.3
# Last edited: 2022-08-06
#
############################################################################################

if [ $# -eq 0 ]; then
  printf '\nThis script creates a template for an entry source file for SBWG.'
  printf '\n\nExpected title of blog entry as argument(s). The title does not '
  printf 'have to be escaped.\n\nA file with a name corrosponding to the '
  printf 'title will be written to the current working directory immediately. '
  printf 'Then a text editor is opened.\n\nExamples:\n'
  printf '%s "An Exciting New Blog Post"\n' "$0"
  printf '%s "My Views On Presidential Pets"\n' "$0"
  printf '%s /home/user/website/entries. "A New Entry"\n' "$0"
  exit
fi

if (( ${#} > 1 )); then
  dir="${1}"
  [[ ${dir: -1} != / ]] && dir="${dir}/"
  shift
fi

title="${1}"
# Choose a file name that corrosponds to the title but excludes spaces and speacial characters
#   according to my personal preferences.
filename=$(printf '%s\n' "${title}"|iconv -f utf8 -t ascii//TRANSLIT|sed -e 's: :_:g'|tr -dc '[:alnum:]-')

[ -f "${dir}${filename:=$(date +%Y-%m-%d_%H-%M-%S_%N)}" ] \
  && {								# If a file of that name already exists here
       printf 'A file with the name %s already exists. '	#   ... inform of the fact and ...
       printf 'No, I'"'"'m not going to overwrite it.\n' \
              "'${dir}${filename}'"
       exit 1							#   ... cancel.
     }

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

printf 'Created file %s.\n' "'${dir}${filename}'"			# Print file name to stdout just for info where stuff has been placed.

declare -i linenumber=5						# This is the line number where the first paragraph will land if there is no additional tagline.
[[ ${SBWG_AUTHOR} ]] && $(( linenumber++ )) 2>/dev/null		# If there is an author tag line, the cursor position needs to be one line lower.

#"${EDITOR:-nano} -u +6,4 ${filename}"
								# I prefer nano and nobody else uses this script as far as I knew when I wrote this. Other editors
								#   would need different cursor positioning arguments.
nano -u +${linenumber},4 "${dir}${filename}"			# Place the curser in the new paragraph.


