#!/bin/sh
# Copyright (C) 2016 Denis 'GNUtoo' Carikli <GNUtoo@no-log.org>
#
# 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.

set -e

EX_DATAERR=65 # data format error from sysexits.h

usage()
{
  echo "Usage: $0 <source_filename> <dest_filename>"
  exit 1
}

if [ $# -ne 2 ] ; then
  usage
fi

input="$1"
output="$2"

# Might not work for very big files
tmpdir="$(mktemp -d)"

pdfimages "${input}" "${tmpdir}/"

# the pdfimages output file format is <destination>-<num>.ppm
# If destination is a directory, it creates filename like "-000.ppm"
# so we get rid if the "-"
find "${tmpdir}" \
     -maxdepth 1 \
     -name "*.ppm" \
     -execdir rename '-' '' {} \;

# Check if .ppm files were created
for file in "${tmpdir}"/0*.ppm ; do
     if [ "${file}" = "${tmpdir}"'/0*.ppm' ]  ; then
	 printf "No images were found inside the PDF.\n"
	 exit "${EX_DATAERR}"
     fi
done

echo "${tmpdir}"/0*.ppm
echo "${tmpdir}"'/0*.ppm'

find "${tmpdir}" \
     -maxdepth 1 \
     -name "*.ppm" \
     -execdir convert {} -resize 25% -quality 80 {}.jpeg \;

find "${tmpdir}" \
     -maxdepth 1 \
     -name "*.jpeg" \
     -execdir convert {} {}.pdf \;

pdfunite "${tmpdir}"/*.pdf "${output}"
rm -rf "${tmpdir}"
du -hs "${output}"
