SHELL=/bin/bash
PROJNAME=PhD

# Files 
SOURCES=*.tex chapters/*.tex
TEXS= PhD.tex

# Commands 
DOCKERIMG = m1dnight/latex:2019
LATEXMK = docker run --rm -i -v "$(CURDIR):$(CURDIR)" -w "$(CURDIR)" --name latex $(DOCKERIMG) latexmk
LMKFLAGS = -shell-escape -synctex=1 -halt-on-error
LATEXINDENT = docker run --rm -it -v "$(CURDIR):$(CURDIR)" -w "$(CURDIR)" $(DOCKERIMG) latexindent
LIFLAGS = -w
MKGLOSS = docker run --rm -i -v "$(CURDIR):$(CURDIR)" -w "$(CURDIR)" --name latex $(DOCKERIMG) makeglossaries
PDFLATEX = docker run --rm -i -v "$(CURDIR):$(CURDIR)" -w "$(CURDIR)" --name latex $(DOCKERIMG) pdflatex
BIBER = docker run --rm -i -v "$(CURDIR):$(CURDIR)" -w "$(CURDIR)" --name latex $(DOCKERIMG) biber
BIBTEX = docker run --rm -i -v "$(CURDIR):$(CURDIR)" -w "$(CURDIR)" --name latex $(DOCKERIMG) bibtex

# Determine OS 
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

.PHONY: $(PROJNAME).pdf all clean
all: $(PROJNAME).pdf

%.tex: %.raw
	./raw2tex $< > $@

%.tex: %.dat
	./dat2tex $< > $@

$(PROJNAME).pdf: $(PROJNAME).tex 
	$(PDFLATEX) -draftmode $<	
	$(MKGLOSS) $(PROJNAME)
	$(BIBTEX) $(PROJNAME)
	$(PDFLATEX) -draftmode $<		
	$(PDFLATEX) $<		

tidy:
	$(LATEXINDENT) $(LIFLAGS) biblio.bib
	@for src in $(SOURCES) ; do \
		echo "Tidying $$src" ; \
		$(LATEXINDENT) $(LIFLAGS) $$src > /dev/null \
	; done

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 "*.bbl" -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 "*.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
	

watch:
ifeq ($(OSFLAG),LINUX)
	inotifywait --exclude "[^t][^e][^x]$$" -e close_write -rmq . | while read edit; do make ; done
endif
ifeq ($(OSFLAG),OSX)
	fswatch -e ".*" -i ".\\.tex$$" . | while read num ; do make; done
endif