#!/usr/bin/env zsh
# This script builds the documentation

echo; echo "---> Deleting old directories"; echo
rm -rf html/
rm -rf docs/

MATLAB=`which matlab`

# Auto-run Matlab, publishing HTML output from optickatest.m
# and optickaBehaviourTest.m
if [[ "$(uname -s)" = "Darwin" ]]; then 
	if [ -f $MATLAB ]; then
		$MATLAB -nodesktop -nosplash -r "Screen('Preference', 'SkipSyncTests', 2);publish('optickaTest.m');sca;close all;clear all;pause(1);publish('optickaBehaviourTest.m');sca;close all;clear all;pause(1);exit"
	fi
else
	if [ -f $MATLAB ]; then
		$MATLAB -nodesktop -nosplash -r "publish('optickaTest.m');sca;close all;clear all;pause(1);publish('optickaBehaviourTest.m');pause(1);exit"
	fi
fi

# We scrape the version number from the main opticka file
VER=$(grep -o -E -e "optickaVersion\schar\s+=\s+'[0-9\.]+'" opticka.m | grep -o -E -e "[0-9\.]+")
echo; echo "---> Opticka version = $VER"; echo
sleep 1
# and then auto-edit the Doxygen file
[ -n $VER ] && sed -i -E "s/^PROJECT_NUMBER.*/PROJECT_NUMBER = $VER/g" .doxyfile
if [ $? -eq 0 ]; then
	echo; echo "---> Edited .doxyfile"; echo
else
	echo; echo "---> Edit .doxyfile FAILED"; echo
fi
sleep 1
echo; echo "---> Will run DOXYGEN"; echo
doxygen .doxyfile
echo; echo "---> Ran doxygen"
#a little cleanup if any rogue files are produced...
[ -f .doxyfilee ] && rm .doxyfilee
[ -f .doxyfile-e ] && rm .doxyfile-e
[ -f debug.txt ] && rm debug.txt
sleep 1
mv html/ docs/

list=("uihelpvars" "uihelpstims" "uihelpstate" "uihelpfunctions" "uihelptask")
for x in $list; do
	pandoc -d "help/help.yaml" -o "help/${x}.html" "help/${x}.md"
done
cp help/*.html docs/

if [[ "$(uname -s)" = "Darwin" ]]; then 
	open docs/index.html
	open docs/optickaTest.html
	open docs/optickaBehaviourTest.html
else
	xdg-open docs/index.html
	xdg-open docs/optickaTest.html
	xdg-open docs/optickaBehaviourTest.html
fi
echo; echo "---> FINISHED!"
exit 0
