#!/bin/bash

# Copyright 2020 babiak
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License

# This program uses code from nytpu's gemlog.sh, also licensed under the GNU AGPL,
# which can be found at https://git.sr.ht/~nytpu/gemlog.sh .
#
# Essentially, this is a stripped-down version of the aforementionned script.

get_post_title() {
	cat "$1" | perl -lne 's/#{1,3}\s*(.*)/\1/ or next; print; exit'
}

gemlog="${GEMLOG:-gemlog.gmi}"
prefix="${PREFIX:-}"

tempfile=$(mktemp)

header=$(cat << EOF
# Babiak's gemlog. 

generated automatically using gemlog_two.sh, based on nytpu's gemlog.sh. link is in the script.

=> /gemlog_two.sh the script

EOF
)

get_post_date() {
	# assumes a git repository. returns date of last modification.
	git log -1 --format="%ad" --date=iso -- "$1" | sed 's/ .*$//'
}

build_entries() {
	# run in the folder you want to index.
	find . -maxdepth 1 -type f -name '*.gmi' -not -empty -print0 | while IFS= read -r -d '' gemfile
	do
		gemfile=$(echo $gemfile|sed 's/\.\///')
		if [[ "$gemfile" == "$gemlog" ]] ;then
			continue
		fi
		printf "=> %s%s %s %s%s\n" "$prefix" "$gemfile" "$(get_post_date $gemfile)" "$prefix" "$(get_post_title $gemfile)"
	done
}

recursion_handler() {
	if [[ "$1" == "-r" ]]
	then
		oldprefix=$prefix
		find . -type d -not -path '*/\.*' -print0 | while IFS= read -r -d '' folder
		do
			pushd $folder >/dev/null
			prefix=$(echo $folder|sed 's/^\(\.\/\|\.\)//')/
			echo "## $prefix"
			recursion_handler
			popd >/dev/null
		done
		prefix=$oldprefix
	else
		build_entries
	fi
}

main(){
	echo "$header" > $tempfile
	recursion_handler $@ >> $tempfile
	mv $tempfile $gemlog
	git add $gemlog 
	git commit -m "updated gemlog index"
}

main $@