#!/bin/bash

set -eo pipefail

# Input variables
FOLDER=${1:-Document}
MASVS_VERSION=${2:-SNAPSHOT}
MASTG_VERSION=${3:-SNAPSHOT}

# You can also use the environment variables below to adapt the build process
IMG=${IMG:-dalibo/pandocker}
TAG=${TAG:-23.03} # /!\ use stable-full for non-european languages
LATEX_TEMPLATE=${LATEX_TEMPLATE:-eisvogel}
TITLE=${TITLE:-OWASP Mobile Application Security Verification Standard ${MASVS_VERSION}}

PANDOC_PARAMS=${PANDOC_PARAMS:-}
PANDOC_PARAMS+="--resource-path=.:${FOLDER} "
PANDOC_PARAMS+="--metadata masvs_version=${MASVS_VERSION} --metadata mastg_version=${MASTG_VERSION} "

# disable captions for images in pandoc
PANDOC_PARAMS+="-fmarkdown-implicit_figures"


[ ! -z "${VERBOSE}" ] && PANDOC_PARAMS+="--verbose "

PANDOCKER="docker run --rm --volume `pwd`:/pandoc ${IMG}:${TAG} ${PANDOC_PARAMS}"

# remove the HTML comment from \pagebreak
docker run --rm --entrypoint '/bin/sh' --volume `pwd`:/pandoc ${IMG}:${TAG} -c "sed -i 's#<!-- \(.*\) -->#\1#g' ${FOLDER}/[0-9][0-9]-*.md"

# convert HTML images to pandoc markdown images
docker run --rm --entrypoint '/bin/sh' --volume `pwd`:/pandoc ${IMG}:${TAG} -c "sed -i -f tools/docker/imagereplace.sed ${FOLDER}/[0-9][0-9]-*.md"

# Use pandocker PANDOCKER by default, unless `export PANDOC=pandoc`
# this is useful for CI, because we can run the script directly inside the container
PANDOC=${PANDOC:-${PANDOCKER}}

METADATA="${FOLDER}/metadata.md"
# Note: chapters for MASVS categories are generated by tools/generate_masvs_md.py using masvs.yaml
CHAPTERS="${FOLDER}/[0-9][0-9]-*.md"
OUTPUT_BASE_NAME="OWASP_MASVS"

[ ! -z "${VERBOSE}" ] && echo "Create PDF"

# header
${PANDOC} \
  --output tmp_latex-header.latex \
  --template tools/docker/latex-header.tex \
  ${METADATA}

# cover
${PANDOC} \
  --output tmp_cover.latex \
  --template tools/docker/cover.tex \
  ${METADATA}

# first_page
${PANDOC} \
  --output tmp_first_page.latex \
  --template tools/docker/first_page.tex \
  ${METADATA}

# PDF
${PANDOC} \
  --template=${LATEX_TEMPLATE} \
  --pdf-engine=xelatex \
  --columns 50 \
  --highlight-style=tango \
  --metadata title="${TITLE}" \
  --include-in-header tmp_latex-header.latex \
  --include-before-body tmp_cover.latex \
  --include-before-body tmp_first_page.latex \
  --output ${OUTPUT_BASE_NAME}.pdf \
  ${METADATA} \
  ${CHAPTERS}

# EPUB
${PANDOC} \
  --metadata title="${TITLE}" \
  --metadata author="Bernhard Mueller, Sven Schleier, Jeroen Willemsen, Carlos Holguera and Jeroen Beckers" \
  --epub-cover-image=cover.png \
  -o ${OUTPUT_BASE_NAME}.epub \
  ${METADATA} \
  ${CHAPTERS}

# clean temp files
rm -f tmp_latex-header.latex tmp_cover.latex tmp_first_page.latex
