#!/bin/sh

LIBFOLDER="."
DOCFOLDER="doc"
PLATFORM=$(uname)
FAUST2MD=$(which faust2md | head -1)

for p in $@; do
	if [ $p = "-help" ] || [ $p = "-h" ]; then
		echo "Just run it! It will automatically look for all the .lib files and generate the corresponding documentation in /doc."
		exit 1
	fi
done

FILES="analyzers.lib basics.lib compressors.lib delays.lib demos.lib dx7.lib envelopes.lib filters.lib hoa.lib interpolators.lib maths.lib misceffects.lib oscillators.lib noises.lib phaflangers.lib physmodels.lib reducemaps.lib reverbs.lib routes.lib signals.lib soundfiles.lib spats.lib synths.lib vaeffects.lib"

mkdir -p tmp/title

echo "% Faust Standard Libraries" > tmp/title/title.md

for p in $FILES; do
	("${FAUST2MD}" "$LIBFOLDER/$p" > tmp/${p%.lib}.md) || exit
done

# Generate the raw html version of the doc
(pandoc --toc --standalone --metadata pagetitle="Faust Libraries Documentation" --include-in-header="$LIBFOLDER/doc/md/header.html" --mathjax "$LIBFOLDER/README.md" "$LIBFOLDER/doc/md/standardFunctions.md" "$LIBFOLDER/doc/md/primitives.md" tmp/*.md "$LIBFOLDER/doc/md/licenses.md" -o "$DOCFOLDER/library.html") || exit

# Generate the PDF doc
(pandoc --toc tmp/title/title.md "$LIBFOLDER/README.md" "$LIBFOLDER/doc/md/standardFunctions.md" "$LIBFOLDER/doc/md/primitives.md" tmp/*.md "$LIBFOLDER/doc/md/licenses.md" -s -o "$DOCFOLDER/library.pdf") || exit

# Reformatting the html file with the right template
if [ $PLATFORM = "Darwin" ]; then
	(sed -i "" "s/<body>/<body><div class=\"container\"><div class=\"row\" style=\"height: 100vh;\">/g" "$DOCFOLDER/library.html") || exit
	(sed -i "" "s/<\/body>/<\/div><\/div><\/body>/g" "$DOCFOLDER/library.html") || exit
	(sed -i "" "s/<nav id=\"TOC\">/<div class=\"col-sm-4\" id=\"TOC\" style=\"height: 100%;overflow: scroll;\">/g" "$DOCFOLDER/library.html") || exit
	(sed -i "" "s/<h1 id=\"faust-libraries\">Faust Libraries<\/h1>/<div class=\"col-sm-8\" style=\"height: 100%;overflow-y: scroll\"><h1 id=\"faust-libraries\">Faust Libraries<\/h1>/g" "$DOCFOLDER/library.html") || exit
else
 	(sed -i 's/<body>/<body><div class=\"container\"><div class=\"row\" style=\"height: 100vh;\">/g' "$DOCFOLDER/library.html") || exit
 	(sed -i 's/<\/body>/<\/div><\/div><\/body>/g' "$DOCFOLDER/library.html") || exit
 	(sed -i 's/<nav id=\"TOC\">/<nav class=\"col-sm-4\" id=\"TOC\" style=\"height: 100%;overflow: scroll;\">/g' "$DOCFOLDER/library.html") || exit
 	(sed -i 's/<h1 id=\"faust-libraries\">Faust Libraries<\/h1>/<div class=\"col-sm-8\" style=\"height: 100%;overflow-y: scroll\"><h1 id=\"faust-libraries\">Faust Libraries<\/h1>/g' "$DOCFOLDER/library.html") || exit
fi

rm -r tmp
