#-------------------------------------------------------------------------------
# Docker variables.
# The latex compiler runs in a docker container so we need to 
# run it as the current user or the produces files are owned by root.
UID := $(shell id -u)
GID := $(shell id -g)

#-------------------------------------------------------------------------------
# Determine OS for find with regex.
OSFLAG :=
ifeq ($(OS),Windows_NT)
	OSLFAG = WIN
else
	UNAME_S := $(shell uname -s)
	ifeq ($(UNAME_S),Linux)
		OSFLAG = LINUX
	endif
	ifeq ($(UNAME_S),Darwin)
		OSFLAG = OSX
	endif
endif

#-------------------------------------------------------------------------------
# Makefile
src = $(wildcard *.tex) 
tidies = $(src:.tex=.tidied)

.PHONY: all 

main.pdf: $(tidies)
	@docker run --rm -it -u $(UID):$(GID) -v "$(CURDIR):$(CURDIR)" -w "$(CURDIR)" m1dnight/latex:2019 latexmk -pdf main.tex > /dev/null
	@touch $@

tidy: $(tidies)

%.tidied: %.tex
	@echo "Tidy ${<}"
	@docker run --rm -it -u $(UID):$(GID) -v "$(CURDIR):$(CURDIR)" -w "$(CURDIR)" m1dnight/latex:2019 latexindent -w $< > /dev/null
	@touch $@

clean:
	@find . -type f \( -name "*.bak" -o \
					   -name "*.pyg" -o \
					   -name "*.bbl" -o \
					   -name "*.aux" -o \
					   -name "*.bcf" -o \
					   -name "*.fdb_latexmk" -o \
					   -name "*.fls" -o \
					   -name "*.dvi" -o \
					   -name "*.acr" -o \
					   -name "*.alg" -o \
					   -name "*.flg" -o \
					   -name "*.glg" -o \
					   -name "*.gls" -o \
					   -name "*.blg" -o \
					   -name "*.log" -o \
					   -name "*.acn" -o \
					   -name "*.out" -o \
					   -name "*.flo" -o \
					   -name "*.glo" -o \
					   -name "*.ist" -o \
					   -name "*.lawl" -o \
					   -name "*.lod" -o \
					   -name "*.mw" -o \
					   -name "*.toc" -o \
					   -name "*.tidied" -o \
					   -name "*.synctex.gz" -o \
					   -name "*.run.xml"  \) -delete
ifeq ($(OSFLAG),LINUX)
	@find . -regextype sed -regex ".*bak[0-9]*" -delete
endif
ifeq ($(OSFLAG),OSX)
	@find -E . -regex ".*bak[0-9]*" -delete
endif