#!/bin/bash

# PDFUnlock
# Copyright (c) 2020 Stephan Brunner <s.brunner@stephan-brunner.net>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

VERSION=0.1

set -e

function findExecutable() {
	E=`which "${1}"`
	if [ ! -x "${E}" ]
	then
		echo $1 not found! >&2
		exit 1
	fi
	echo -n $E
}

PSTOPDF=$(findExecutable ps2pdf)
PDFTOPS=$(findExecutable pdftops)
PDFINFO=$(findExecutable pdfinfo)
PDFUNITE=$(findExecutable pdfunite)
MKTEMP=$(findExecutable mktemp)

if [ $# -ne 2 ]
then
	echo "PDFUnlock v${VERSION}"
	echo "Copyright (c) 2020 Stephan Brunner <s.brunner@stephan-brunner.net>"
	echo
	echo Usage: $0 [Locked PDF] [Unlocked PDF]
	exit 2
fi

LOCKED_PDF=${1}
UNLOCKED_PDF=${2}

if [ ! -r "${LOCKED_PDF}" ]
then
	echo Cannot read locked pdf
	exit 3
fi

rm "${UNLOCKED_PDF}" >/dev/null 2>&1 || true
touch "${UNLOCKED_PDF}" >/dev/null 2>&1 || true

if [ ! -w "${UNLOCKED_PDF}" ]
then
	echo Cannot write unlocked pdf
	exit 4
fi

NUMPAGES=$(pdfinfo "${LOCKED_PDF}" | grep Pages | awk '{print $2}')
echo Detected $NUMPAGES pages...

if ! [[ "${NUMPAGES}" =~ ^[0-9]+$ ]]
then
	echo Could not determine number of pages.
	exit 5
fi

if [ $NUMPAGES -le 0 ]
then
	echo Locked PDF is empty.
	exit 6
fi

TMPDIR=$($MKTEMP -d)
CONCATLIST=""

for (( PAGE=1; PAGE<=$NUMPAGES; PAGE++ ))
do
	echo Processing page $PAGE...
	$PDFTOPS -eps -f $PAGE -l $PAGE "${LOCKED_PDF}" $TMPDIR/page.$PAGE.eps
	$PSTOPDF -dEPSCrop $TMPDIR/page.$PAGE.eps $TMPDIR/page.$PAGE.pdf
	CONCATLIST="${CONCATLIST} $TMPDIR/page.$PAGE.pdf"
done

echo Generating final PDF...
$PDFUNITE ${CONCATLIST} "${UNLOCKED_PDF}"

echo Cleaning up...
rm -R $TMPDIR

