#!/bin/bash

# Attempt to make a PDF of the whole text, using pandoc.
#
# All being well, the generated PDF will appear as book.pdf in your current directory.

if [ $# -eq 0 ]; then
    echo "Usage: $0 filename.md"
    exit 1
fi

name=$(basename $1 .md)
outdir=$(pwd)
srcdir=$(cd -- $(dirname "$1") && pwd)
path=$(cd -- $(dirname "$0") && pwd)

# Git branch name - used on the title page and metadata
git_branch=$(git branch --show-current 2>/dev/null || echo 'unknown')
export UE_GIT_BRANCH=${git_branch^}

# Git commit hash - used on the title page
export UE_GIT_COMMIT=$(git log -1 --format="%h" 2>/dev/null)

# For finding the logging script
export LUA_PATH="$path/filters/?.lua;;"

# For finding the Solidity highlighting
export TEXINPUTS="$path/inc/:"

cd $srcdir

echo "Converting $srcdir/$name.md to ./$name.pdf with version $UE_GIT_BRANCH"

cat $name.md | \
    sed 's|\(images/diagrams\)/\([^)]*\)\.svg|\1_pdf/\2.pdf|g' | \
    pandoc \
        --output $outdir/$name.pdf \
        --from markdown \
        --metadata title-meta:"Upgrading Ethereum - ${UE_GIT_BRANCH^} Edition" \
        --metadata author-meta:'Ben Edgington' \
        --metadata lang:en-GB \
        --lua-filter $path/filters/pagebreaks.lua \
        --lua-filter $path/filters/links.lua \
        --lua-filter $path/filters/figures.lua \
        --lua-filter $path/filters/summaries.lua \
        --lua-filter $path/filters/linebreaks.lua \
        --lua-filter $path/filters/codeblocks.lua \
        --variable documentclass:book \
        --variable classoption:oneside \
        --variable linkcolor:violet \
        --variable geometry:a4paper \
        --variable geometry:margin=2.54cm \
        --variable block-headings \
        --variable monofont:'DejaVu Sans Mono' \
        --include-before-body $path/inc/title-page.tex \
        --include-in-header $path/inc/header.tex \
        --toc \
        --toc-depth 3 \
        --no-highlight \
        --pdf-engine xelatex
