#! /bin/bash

############################################################################################
#
# genentry - Script to generate a new entry source file for SBWG v0.8 or later
# Version: 0.2.2
# Last edited: 2021-12-05
#
############################################################################################

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 "$0 /home/user/website/entries. \"A New Entry\""
  echo
  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=$(echo "${title}"|sed -e 's: :_:g'|tr -d '.!\"§$%&()[]{}?´`#\\/:*?"<>|[:space:]')
filename=$(echo "${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)}" ] \
  && { echo "A file with the name '${dir}${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.
} > "${dir}${filename}" || exit 1				# End here if the file can not be written.

echo "Created file '${dir}${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. Other editors would need
								#   different cursor positioning arguments.
nano -u +6,4 "${dir}${filename}"				# Place the curser in the new paragraph.
