#!/bin/bash

# Add the metadata if the answer is not empty
# Usage:
#	append_to_metadata file_name metadata_name
append_to_metadata() {
	if [ $# -eq 2 ]; then
		echo -n "$2 : "
		read answer
		option="$(echo "$2" | tr '[:upper:]' '[:lower:]')"
		if [ -n "$answer" ]; then
			echo "$option = ""$answer" >> "content/articles/$1"
		else
			echo "Empty answer, nothing was appended"
		fi
	fi
}

echo -n "Filename : "
read filename

echo "+++" > content/articles/"$filename"

echo "The title must be between quotes"

append_to_metadata "$filename" "Title"

append_to_metadata "$filename" "Date"

append_to_metadata "$filename" "Draft"

append_to_metadata "$filename" "Slug"

echo "[taxonomies]" >> content/articles/"$filename"

echo "Categories and tag must be formatted as follows : [\"element1\",\"element2\"]"

append_to_metadata "$filename" "Categories"

append_to_metadata "$filename" "Tags"

echo -e "+++\n\n" >> content/articles/"$filename"

# Try to get the default editor from alternatives
EDITOR=${EDITOR:-$(update-alternatives --list editor | head -n1)}
# If not present set it to vi
EDITOR=${EDITOR:-vi}

# Open the newly created file, hopefully in the chosen editor
if [ -n "$EDITOR" ]; then
	$EDITOR content/articles/"$filename"
fi
