#!/bin/sh

# Interestings options:
# --opts="-P full.bleed=1" => add crop margins for print PDF for Lulu
# --opts="-P pdf.color.scheme=gray-scale" => gray scale PDF for Lulu POD service
# --opts="-V" => verbose mode of dblatex
# --lang=de-DE => build a translation

set -e

. $(dirname $0)/common.sh

check_cwd

OPT_lang="en-US"
version=$(get_product_version)
topdir=$(pwd)

parse_options "$@"

if [ ! -e tmp/$OPT_lang/xml ] || [ -z "$OPT_skip" ]; then
    publican build --config=publican-pdf.cfg --formats=xml --langs=$OPT_lang
    if ! grep "<book " tmp/$OPT_lang/xml/debian-handbook.xml | grep -q "lang="; then
	sed -i -e "s/<book/<book lang=\"${OPT_lang}\"/" tmp/$OPT_lang/xml/debian-handbook.xml
    fi

    if [ -n "$OPT_paperback" ]; then
	sed -i -e '/<media/,/<\/media/d' tmp/$OPT_lang/xml/Book_Info.xml
    fi
fi

cp -a bin/dblatex tmp/$OPT_lang/xml/
cd tmp/$OPT_lang/xml/

echo "RUN: dblatex -c dblatex/librement.conf $OPT_opts debian-handbook.xml"
if dblatex -c dblatex/librement.conf $OPT_opts debian-handbook.xml; then
    targetdir="$topdir/publish/$OPT_lang/Debian/$version/pdf/debian-handbook"
    mkdir -p $targetdir
    if ! pdfinfo debian-handbook.pdf > /dev/null;
    then
        mutool clean debian-handbook.pdf debian-handbook.pdf
    fi
    cp debian-handbook.pdf $targetdir/
    pdfinfo $targetdir/debian-handbook.pdf
    echo "SUCCESS: $targetdir/debian-handbook.pdf"
else
    echo "ERROR: Failed to build PDF version for $OPT_lang"
    exit 1
fi

