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