#!/usr/bin/env bash
#
# PDF Fonts Embedder
# Copyright (C) 2009-2026 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: dreibh@simula.no
#

# Bash options:
set -eu


# ###### Usage ##############################################################
usage () {
   echo >&2 "Usage: $0 input_pdf output_pdf [-O|--optimise|--optimize] [-h|--help]"
   exit 1
}


# ###### Main program #######################################################

# ====== Handle arguments ===================================================
GETOPT="$(PATH=/usr/local/bin:${PATH} which getopt)"
options="$(${GETOPT} -o Oh --long optimise,optimize,help -a -- "$@")"
# shellcheck disable=SC2181
if [[ $? -ne 0 ]]; then
   usage
fi

OPTIMISE=0
eval set -- "${options}"
while [ $# -gt 0 ] ; do
   case "$1" in
      -O | --optimise | --optimize])
         OPTIMISE=1
         shift
         ;;
      -h | --help)
         usage
         # shift
         ;;
      --)
         shift
         break
         ;;
  esac
  shift
done
if [ $# -ne 2 ] ; then
   usage
fi
INPUT_PDF="$1"
OUTPUT_PDF="$2"
if [ ! -e "${INPUT_PDF}" ] ; then
   echo >&2 "ERROR: PDF file ${INPUT_PDF} does not exist!"
   exit 1
fi


# ====== Perform conversion =================================================

# ------ Using PDF/X --------------------------------------------------------
if [ ${OPTIMISE} -eq 1 ] ; then
   ( ps2pdf -dPDFSETTINGS=/prepress -dCompatibilityLevel=1.7 "${INPUT_PDF}" "${OUTPUT_PDF}"-tmp.pdf && qpdf --linearize "${OUTPUT_PDF}"-tmp.pdf "${OUTPUT_PDF}" ) || cp "${INPUT_PDF}" "${OUTPUT_PDF}"
   rm -f "${OUTPUT_PDF}"-tmp.pdf
else
    ps2pdf -dPDFSETTINGS=/prepress -dCompatibilityLevel=1.7 "${INPUT_PDF}" "${OUTPUT_PDF}"
fi
