#!/bin/sh
#
# PDF Font Embedder
# Copyright (C) 2009-2022 by Thomas Dreibholz
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# Contact: thomas.dreibholz@gmail.com
#

# ====== Get arguments ======================================================
if [ $# -lt 2 ] ; then
   echo >&2 "Usage: $0 [Input PDF] [Output PDF] {-optimize}"
   exit 1
fi

INPUT_PDF="$1"
OUTPUT_PDF="$2"

OPTIMIZE=0
if [ "$3" = "-optimize" ] ; then
   OPTIMIZE=1
fi

if [ ! -e "$INPUT_PDF" ] ; then
   echo >&2 "ERROR: PDF file $INPUT_PDF does not exist!"
   exit 1
fi


# ====== Perform conversion =================================================
# ------ Using PDF -> PS -> PDF ---------------------------
# ( ps2pdf -dPDFSETTINGS=/prepress -dLanguageLevel=3 $1 - | \
#      ps2pdf -dPDFSETTINGS=/prepress -dCompatibilityLevel=1.4 - $2-tmp.pdf && \
#  qpdf --linearize $2-tmp.pdf $2  ) || cp $1 $2
# rm -f $2-tmp.pdf

# ------ Using PDF/X --------------------------------------
if [ $OPTIMIZE -eq 1 ] ; then
   ( ps2pdf -dPDFX $1 $2-tmp.pdf && qpdf --linearize $2-tmp.pdf $2 ) || cp $1 $2
   rm -f $2-tmp.pdf
else
    ps2pdf -dPDFX $1 $2
fi
