#! /bin/bash
set -e
# Program: generate-diary
# Version: 0.0.1 (prototype)

# Description: Diary pager for html files
#   This script scans a file tree matching the glob 20*/*/*/, and will build a
#   REAME.html file for each leaf directory which will paginate diary entries,
#   allowing to go to the next or previous one in a single click after having
#   read the entry.

# Bugs:
#   - inflexible: works only for the XXIst century
#   - does not do anything when a README.html exists, this prevents updates.

# Copyright 2019 Étienne Mollier <etienne.mollier@mailoo.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# produce a lovely pager to go to the next, or the previous diary entry
create_pager () {
	prev="$1"
	next="$2"

	printf '<center><br/>\n'
	if [ "$prev" = "" ]
	then
		printf 'Début du journal&nbsp; —&nbsp; '
		printf '<a href="../../../%s/" rel="next">'  "$next"
		printf '%s →</a>\n'                  "${next//\//-}"
	elif [ "$next" = "" ]
	then
		printf '<a href="../../../%s/" rel="prev">'  "$prev"
		printf '← %s</a>&nbsp; —&nbsp; '     "${prev//\//-}"
		printf 'Dernière entrée de journal\n'
	else
		printf '<a href="../../../%s/" rel="prev">'  "$prev"
		printf '← %s</a>&nbsp; —&nbsp; '     "${prev//\//-}"
		printf '<a href="../../../%s/" rel="next">'  "$next"
		printf '%s →</a>\n'                  "${next//\//-}"
	fi
	printf '<br/></center>\n'
}

run1="true"
for entry in 20*/*/*/ ""  # note that the last iteration is empty
do
	# strip trailing slash
	entry="${entry%*/}"

	# first iteration, just initialize next
	if "$run1"
	then
		next="$entry"
		run1="false"
		continue
	fi

	# general case dealing with diary entries
	prev="$today"
	today="$next"
	next="$entry"

	cd "$today"
	if [ -e "README.html" ]
	then
		printf '%s has a README.html already\n' "$today"
		if grep -q 'rel="prev"' README.html \
		   && ! grep -q 'rel="next"' README.html
		then
			printf 'Stop: last entry hit on %s.\n' "$today"
			printf '    You may want to clean %s/README.html ' \
				"$today"
			printf 'before repaging newer entries.\n'
		fi
	else
		printf 'paging diary entry from %s\n' "$today"
		create_pager "$prev" "$next" >> README.html
	fi
	cd - >/dev/null # for some reason, popd commands are noisy
done
