#!/bin/bash

# exit whenever a command fails
set -e

CODEDIR="../src"

check_existence()
{
	make -C "$CODEDIR" "$@"

	# check whether $(CODEDIR)/lbmat_$(MODEL) exists
	for target in "$@"; do
		target="$CODEDIR/$target"
		if [[ ! -f "$target" ]]; then
			echo "$target still does not exist -> check manually"
			exit 1
		fi
	done
}

#echo $(realpath $0)
#MODEL="d1q3_ade"
# automatic model selection based on directory name
#RP=$(realpath $0)
RP1=`pwd`
#RP1={${RP%/*}
MODEL=${RP1##*/}

echo model: ${MODEL}

# make all necessary binaries
check_existence lbmat_${MODEL} simplify export_latex export_latex_compare

# execute lbmat_${MODEL} to create output directories
${CODEDIR}/lbmat_${MODEL}

# make symlinks
[[ ! -f simplify ]] && ln "${CODEDIR}/simplify" simplify -s
[[ ! -d latex ]] && ln "../latex" latex -s

# symbolic substitutions
for a in output*symbolic; do
	if [ ! -f "${a}/spatial_EPDE/pde_00.tex" ]; then
		../scripts/script_backsubst_searcher.py ${a}
		"$CODEDIR/export_latex" ${a}
	fi
	# check whether latex files exist
	if [ ! -f "${a}/spatial_EPDE/pde_00.tex" ]; then
		echo "${a}/spatial_EPDE/pde_00.tex not found"
		exit;
	fi
	# for compatibility reasons
	if [ ! -f "${a}/spatial_EPDE/pde_00.txt" ]; then
		../scripts/script_backsubst_searcher.py ${a}
		"$CODEDIR/export_latex" ${a}
	fi
	if [ ! -f "${a}/spatial_EPDE/pde_00.txt" ]; then
		echo "${a}/spatial_EPDE/pde_00.txt not found"
		exit;
	fi
	# check symbolic links
	if [ ! -f "${a}_pde_00.txt" ]; then
		ln "${a}/spatial_EPDE/pde_00.txt" "${a}_pde_00.txt" -s
	fi
	if [ ! -f "${a}_pde_01.txt" ]; then
		if [ -f "${a}/spatial_EPDE/pde_01.txt" ]; then
			ln "${a}/spatial_EPDE/pde_01.txt" "${a}_pde_01.txt" -s
		fi
	fi
	if [ ! -f "${a}_pde_02.txt" ]; then
		if [ -f "${a}/spatial_EPDE/pde_02.txt" ]; then
		ln "${a}/spatial_EPDE/pde_02.txt" "${a}_pde_02.txt" -s
		fi
	fi
	if [ ! -f "${a}_pde_03.txt" ]; then
		if [ -f "${a}/spatial_EPDE/pde_03.txt" ]; then
		ln "${a}/spatial_EPDE/pde_03.txt" "${a}_pde_03.txt" -s
		fi
	fi
done

# compare latex
"$CODEDIR/export_latex_compare" output_${MODEL}

# call latex
buf_size=100000000
#TEXCOMP="lualatex"
TEXCOMP="pdflatex"
TEXFILE=supp_${MODEL}

${TEXCOMP} ${TEXFILE}
bibtex ${TEXFILE}
${TEXCOMP} ${TEXFILE}
${TEXCOMP} ${TEXFILE}

rm -f *.aux *.bbl *.blg *.stl *.log *.out *.toc

echo "script finished"
