#!/bin/bash

orig="${PWD}"

if ! command -v asciidoctor &> /dev/null;
then
        exit 0
fi

set -e

for f in $(find . -type f -iname "README.adoc"); do
        filename=$(basename -- "${f}")
	docsdir=$(dirname -- "${f}")
        nosuffix="${filename%.*}"
	pfx="${docsdir}/${nosuffix}"

	newf="${pfx}.html"
        asciidoctor -a ROOTDIR="${orig}/" -o "${newf}" "${f}"
	echo "Generated ${newf} from ${f}"
        git add "${newf}"
        if command -v asciidoctor-pdf &> /dev/null;
	then
		newf="${pfx}.pdf"

        	asciidoctor-pdf -a ROOTDIR="${orig}/" -o "${newf}" "${f}"
	fi
        if command -v pandoc &> /dev/null;
        then
		newf="${pfx}.md"

		set +e
                #asciidoctor -a ROOTDIR="${orig}/" -b docbook -o - "${f}" | pandoc -f docbook -t markdown_strict -o "${newf}"
                #asciidoctor -a ROOTDIR="${orig}/" -b html -o - "${f}" | pandoc -f html -t markdown_strict -o "${newf}"
                asciidoctor -a ROOTDIR="${orig}/" -b html -o - "${f}" | pandoc -f html -t gfm -o "${newf}"
		if [ $? -eq 0 ];
		then
			echo "Generated ${newf} from ${f}"
	                git add "${newf}"
		else
			echo "Failed to generate ${newf} from ${f}"
			git rm "${newf}" 2>/dev/null
		fi
		set -e
        fi
	cd ${orig}
done
echo "Regenerated docs"
