#!/bin/sh

WATER_PDF_FILE="${1}"
OLD_WATER="${2}"

if [ -z "${3}" ]; then
	NEW_WATER=""
else
	NEW_WATER="${3}"
fi


if [ -f "${WATER_PDF_FILE}" ]; then
	printf '%s\n' "Replace '${OLD_WATER}' with '${NEW_WATER}' for the PDF file : ${WATER_PDF_FILE}"

	BASE_DIR=$(dirname ${WATER_PDF_FILE})
	BASE_NAME=$(basename ${WATER_PDF_FILE})
	UNCOMPRESS_PDF_FILE="${BASE_DIR}/uncompress_${BASE_NAME}"
	UNWATER_PDF_FILE="${BASE_DIR}/unwater_${BASE_NAME}"

	command pdftk "${WATER_PDF_FILE}" output "${UNCOMPRESS_PDF_FILE}" uncompress

	sed -e "s/${OLD_WATER}/${NEW_WATER}/g" "${UNCOMPRESS_PDF_FILE}" >"${UNWATER_PDF_FILE}"

	command pdftk "${UNWATER_PDF_FILE}" output "${WATER_PDF_FILE}" compress

	rm -f "${UNCOMPRESS_PDF_FILE}" "${UNWATER_PDF_FILE}"

	exit 0
else
	printf '%s\n' "Error with the first arg : ${1}"
	exit 1
fi