#!/bin/bash

set -e
set -x

# requires inkscape
./make-eps-illus.sh
cp ./source/_static/illustrations/pinguin/* ./source/_static/illustrations/

mkdir -p build

cd source

# generate content tex files from individual rst sources

cat _tex/pre.tex >pocket-reform-handbook.tex

for section in \
  toc \
  preface \
  safety \
  quickstart \
  input \
  linux \
  desktops \
  software \
  hardware \
  advanced \
  schematics \
  online \
  credits
do
  cat $section.rst | grep -v '`KiCad: ' | grep -v '`PDF: ' | pandoc -o _$section.tex -frst+smart --verbose -V fontsize=10pt --top-level-division=chapter
  cat _tex/section.tex >>pocket-reform-handbook.tex
  sed 's/\(-icon\)\.png/\.icon/g' _$section.tex >>pocket-reform-handbook.tex
done

sed -i 's/\.png/\.eps/g' pocket-reform-handbook.tex
sed -i 's/\.icon/\.png/g' pocket-reform-handbook.tex

cat _tex/post.tex >>pocket-reform-handbook.tex

# generate pocket-reform-handbook.pdf
xelatex --interaction=nonstopmode pocket-reform-handbook.tex
# thrice to get the TOC right
xelatex --interaction=nonstopmode pocket-reform-handbook.tex
xelatex --interaction=nonstopmode pocket-reform-handbook.tex

# clean up
ghostscript -sDEVICE=pdfwrite -dCompatibilityLevel=1.5 -dPDFSETTINGS=/printer -dNOPAUSE -dQUIET -dBATCH -sOutputFile=../build/pocket-reform-handbook.pdf pocket-reform-handbook.pdf
rm -- _*.tex
rm -- *.out
rm -- *.log
rm -- *.aux
rm -- *.toc

cd ..

echo ">>> generated ./build/pocket-reform-handbook.pdf <<<"
