#!/bin/sh
# Regenerate ../thesis.docx from the LaTeX sources.
# Needs: tectonic (or xelatex), pandoc >= 2.11, poppler (pdftoppm), python3 with Pillow.
set -e
cd "$(dirname "$0")"
mkdir -p aux img
(cd .. && tectonic -X compile --keep-intermediates --outdir docx_build/aux thesis.tex)   # label numbers
for f in ../figures/*.pdf; do pdftoppm -png -r 220 -singlefile "$f" "img/$(basename "${f%.pdf}")"; done
python3 prep.py snips && tectonic -X compile snips.tex && pdftoppm -png -r 220 snips.pdf sn
python3 - <<'PY'
from PIL import Image, ImageChops
import glob
names = ["fig_placements", "fig_typegraph", "alg1", "alg2", "alg3", "fig_architecture"]
for f, n in zip(sorted(glob.glob("sn-*.png")), names):
    im = Image.open(f).convert("RGB")
    b = ImageChops.difference(im, Image.new("RGB", im.size, "white")).getbbox()
    im.crop((max(0, b[0]-20), max(0, b[1]-20), min(im.width, b[2]+20), min(im.height, b[3]+20))).save(f"img/{n}.png")
PY
python3 prep.py
pandoc body.tex -f latex -t docx -o thesis_raw.docx --metadata-file=meta.yaml --citeproc \
  --bibliography ../references.bib --csl ieee.csl --reference-doc reference.docx --toc --toc-depth 2 --resource-path=.
python3 post.py thesis_raw.docx ../thesis.docx
