#!/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

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 "-"
for ppm in $(ls ${tmpdir} | grep "\.ppm$") ; do
  mv "${tmpdir}/${ppm}" "${tmpdir}/$(echo ${ppm} | sed 's#^-##')"
done

files="$(ls ${tmpdir}/*.ppm | sed 's#\.ppm$##' )"
for filenum in ${files} ; do
  # Converting directly in pdf result in awful image quality (cause unknown)
  convert "${filenum}.ppm" -resize 25% -quality 80 "${filenum}.jpeg"
  convert "${filenum}.jpeg" "${filenum}.pdf"
done

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