#!/usr/bin/sh
#
# 	Part of kde-service-menu-pdf Version 2.3
# 	Copyright (C) 2007-2019 Giuseppe Benigno <giuseppe.benigno(at)gmail.com>
#
# 	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/>.
#

new_line="
"

#### languages strings messages #################
# Syntax for strings name is: msg_[$action]_$window_[$section]
# For languages as sr@Latn use srLatn

load_language_de () {
	msg_common_software_not_found_title="Komponente wurde nicht gefunden"
	msg_common_pdfinfo_not_found_text="Die pdfinfo Software wurde nicht gefunden! Bitte installieren Sie poppler-utils."
	msg_common_pdftoppm_not_found_text="Die pdftoppm Software wurde nicht gefunden! Bitte installieren Sie poppler-utils."
	msg_common_action_not_found_text="Die angeforderte Aktion ist nicht implementiert."
	msg_common_file_not_found="Datei nicht gefunden."
	msg_common_finish_title="Konvertierung des Dokuments \"${file_name}\""
	msg_common_finish_ok="Fertig."
	msg_common_finish_error="Ein Fehler ist aufgetreten."

	msg_insert_password_title="Passwort eingeben"
	msg_insert_password_usr="Bitte das Benutzerpasswort für \"${file_name}\" eingeben:"
	msg_insert_password_own="Bitte das Masterpasswort für \"${file_name}\" eingeben:"

	msg_input_pages_range_title="Seitenbereich eingeben"
	msg_input_pages_range="Der Bereich wird durch die folgende Syntax definiert: ZUERST-ZULETZT${new_line}ZUERST und ZULETZT sind jeweils die erste und letzte Seite des Bereichs.${new_line}Wenn Sie auf die letzte Seite des Dokuments verweisen möchten, lassen Sie die Nummer weg.${new_line}${new_line}Beispiele:${new_line}  3 wird nur auf Seite 3 verarbeitet${new_line}  3- werden Seiten bis zur letzten 3 bearbeitet${new_line}  5-8 Seiten 5 bis 8 werden bearbeitet.${new_line}  -8 Seiten werden von 1 bis 8 verarbeitet${new_line}${new_line}Geben Sie den zu bearbeitenden Seitenbereich ein:"

	msg_options_title="Eigenschaften"
	msg_options="Optionen für die Umwandlung von \"${file_name}\" auswählen"

	msg_dpi_title="Auflösung, in DPI"
	msg_dpi="Umwandlung von \"${file_name}\". Auflösung in DPI festlegen (standard ist 150):"

	msg_options_color="Eine farbige PPM-Datei erstellen"
	msg_options_gray="Eine Graustufen-PGM-Datei erstellen"
	msg_options_mono="Eine s/w PBM-Datei erstellen"

	msg_images_root_name_title="Bilderpräfix eingeben"
	msg_images_root_name="Die Bilder werden nach einem Präfix (ohne Leerzeichen) gefolgt von einer Nummer benannt. (${file_name}-000.ppm, ${file_name}-001.ppm ...). Präfix ändern oder den Standardwert lassen:"

	msg_dest_dir="${base_file_name} (bilder)"
	msg_create_dir_error="Kann das Zielverzeichnis für die Bilddateien nicht erstellen!"
}

load_language_en () {
	msg_common_software_not_found_title="Component not found"
	msg_common_pdfinfo_not_found_text="Software pdfinfo not found! Please, install poppler-utils."
	msg_common_pdftoppm_not_found_text="Software pdftoppm not found! Please, install poppler-utils."
	msg_common_action_not_found_text="The requested action is not implemented."
	msg_common_file_not_found="File not found."
	msg_common_finish_title="Conversion of document \"${file_name}\""
	msg_common_finish_ok="Done."
	msg_common_finish_error="An error has occurred."

	msg_insert_password_title="Insert password"
	msg_insert_password_usr="Please insert user password of document \"${file_name}\":"
	msg_insert_password_own="Please insert main password of document \"${file_name}\":"

	msg_input_pages_range_title="Input pages range"
	msg_input_pages_range="The range is defined by the following syntax: FIRST-LAST${new_line}FIRST and LAST are, respectively, the first and last page of the range.${new_line}If you want to refer to the last page of the document , omit the number.${new_line}${new_line}Examples:${new_line}  3 will be processed only on page 3${new_line}  3- will be processed pages from number 3 up to the last${new_line}  5-8 pages 5 to 8 will be processed${new_line}  -8 pages will be processed from 1 to 8${new_line}${new_line}Enter the range of pages to be processed:"

	msg_dpi_title="Resolution, in DPI"
	msg_dpi="Conversion of \"${file_name}\". Set resolution in DPI (default is 150):"

	msg_options_title="Preferences"
	msg_options="Select options for conversion of \"${file_name}\""
	msg_options_color="generate a color PPM file"
	msg_options_gray="generate a grayscale PGM file"
	msg_options_mono="generate a monochrome PBM file"

	msg_images_root_name_title="Insert pictures prefix"
	msg_images_root_name="The images name will be made by a prefix (without spaces) followed by a progressive number (${file_name}-000.ppm, ${file_name}-001.ppm ...). Change prefix for images or leave default value:"

	msg_dest_dir="${base_file_name} (images)"
	msg_create_dir_error="Unable to create the images destination directory!"
}

load_language_fr () {
	msg_common_software_not_found_title="Composant non trouvé"
	msg_common_pdfinfo_not_found_text="Logiciel pdfinfo non trouvé! S'il vous plaît, installez poppler-utils."
	msg_common_pdftoppm_not_found_text="Logiciel pdftoppm non trouvé! S'il vous plaît, installez poppler-utils."
	msg_common_action_not_found_text="L'action demandée n'est pas implémentée."
	msg_common_file_not_found="Fichier non trouvé."
	msg_common_finish_title="Conversion du document \"${file_name}\""
	msg_common_finish_ok="Terminée."
	msg_common_finish_error="Une erreur est survenue"

	msg_insert_password_title="Saisissez le mot de passe"
	msg_insert_password_usr="Saisissez le mot de passe utilisateur pour \"${file_name}\":"
	msg_insert_password_own="Saisissez le mot de passe Administrateur pour \"${file_name}\":"

	msg_input_pages_range_title="Sélection de pages"
	msg_input_pages_range="La plage est définie par la syntaxe suivante: PREMIER-DERNIER${new_line}PREMIER et DERNIER sont respectivement la première et la dernière page de la plage.${new_line}Si vous souhaitez vous référer à la dernière page du document, omettez le numéro.${new_line}${new_line}Exemples:${new_line}  3 seront traités uniquement à la page 3${new_line}  3- seront traitées pages du numéro 3 à la dernière${new_line}  5-8 pages 5 à 8 seront traitées${new_line}  -8 pages seront traitées de 1 à 8${new_line}${new_line}Entrez la plage de pages à traiter:"

	msg_dpi_title="Résolution, en DPI"
	msg_dpi="Conversion de \"${file_name}\". Réglez la résolution en DPI (par défaut: 150):"

	msg_options_title="Préferences"
	msg_options="Sélectionnez les options de conversion pour \"${file_name}\""
	msg_options_color="générer un fichier PPM couleurs"
	msg_options_gray="générer un fichier PPM niveaux de gris"
	msg_options_mono="générer un fichier PPM noir et blanc"

	msg_images_root_name_title="Insérer un préfixe pour les images"
	msg_images_root_name="Notes: les noms des images seront faits d'un préfixe suivi d'un nombre progressif: (${file_name}-000.ppm, ${file_name}-001.ppm ...). Changez le préfixe pour les images ou gardez le préfixe par défaut:"

	msg_dest_dir="${base_file_name} (images)"
	msg_create_dir_error="Impossible de créer le repertoire de destination des images!"
}

load_language_it () {
	msg_common_software_not_found_title="Componente non trovato"
	msg_common_pdfinfo_not_found_text="Il software pdfinfo non è stato trovato! Per favore, installa poppler-utils."
	msg_common_pdftoppm_not_found_text="Il software pdftoppm non è stato trovato! Per favore, installa poppler-utils."
	msg_common_action_not_found_text="L'azione richiesta non è implementata."
	msg_common_file_not_found="File non trovato."
	msg_common_finish_title="Conversione del documento \"${file_name}\""
	msg_common_finish_ok="Conclusa."
	msg_common_finish_error="Si è verificato un errore."

	msg_insert_password_title="Inserisci password"
	msg_insert_password_usr="Per favore digita la password utente per \"${file_name}\":"
	msg_insert_password_own="Per favore digita la password principale per \"${file_name}\":"

	msg_input_pages_range_title="Selezione intervallo"
	msg_input_pages_range="L'intervallo viene definito tramite la seguente sintassi: PRIMA-ULTIMA${new_line}PRIMA e ULTIMA sono, rispettivamente, la prima e l'ultima pagina dell'intervallo.${new_line}Se ci si vuole riferire all'ultima pagina del documento, omettere il numero.${new_line}${new_line}Esempi:${new_line}  3	verrà elaborata solo la pagina 3${new_line}  3-	veranno elaborate le pagine dalla numero 3 fino all'ultima${new_line}  5-8	verranno elaborate le pagine dalla 5 alla 8${new_line}  -8	verranno elaborate le pagine dalla 1 alla 8${new_line}${new_line}Inserire l'intervallo di pagine da elaborare:"

	msg_dpi_title="Risoluzione, in DPI"
	msg_dpi="Conversione di \"${file_name}\". Imposta la risoluzione in DPI (150 é il valore predefinito):"

	msg_options_title="Preferenze"
	msg_options="Seleziona le opzioni per la conversione di \"${file_name}\""
	msg_options_color="genera un file immagine PPM a colori"
	msg_options_gray="generate un file immagine PGM in scala di grigi"
	msg_options_mono="genera un file immagine PBM monocromatico"

	msg_images_root_name_title="Inserisci il prefisso per le immagini"
	msg_images_root_name="Il nome delle immagini, sará composto da un prefisso (senza spazi) seguito da un numero crescente (${file_name}-000.ppm, ${file_name}-001.ppm ...). Cambia il prefisso per le immagini o lascia il valore predefinito:"

	msg_dest_dir="${base_file_name} (immagini)"
	msg_create_dir_error="Non é possibile creare la directory di destinazione per le immagini!"
}

load_language_ru () {
	msg_common_software_not_found_title="Компонент не найден"
	msg_common_pdfinfo_not_found_text="Программное обеспечение pdfinfo не найдено! Установите poppler-utils."
	msg_common_pdftoppm_not_found_text="Программное обеспечение pdftoppm не найдено! Установите poppler-utils."
	msg_common_action_not_found_text="Запрошенное действие не выполнено."
	msg_common_file_not_found="Файл не найден."
	msg_common_finish_title="Преобразование документа \"${file_name}\""
	msg_common_finish_ok="Готово."
	msg_common_finish_error="Произошла ошибка."

	msg_insert_password_title="Вставить пароль"
	msg_insert_password_usr="Пожалуйста, вставьте пароль пользователя для документа \"${file_name}\":"
	msg_insert_password_own="Пожалуйста, вставьте основной пароль для документа \"${file_name}\":"

	msg_input_pages_range_title="Диапазон входящих страниц"
	msg_input_pages_range="Диапазон определяется следующим синтаксисом: ПЕРВЫЙ-ПРОШЛОЙ${new_line}ПЕРВЫЙ и ПРОШЛОЙ - соответственно, первая и последняя страница диапазона.${new_line}Если вы хотите обратиться к последней странице документа, опустите номер.${new_line}${new_line}Примеры:${new_line}  3 будут обработаны только на странице 3${new_line}  3- будут обрабатываться страницы от номера 3 до последнего${new_line}  5-8 страниц с 5 по 8 будут обработаны${new_line}  -8 страниц будет обработано от 1 до 8${new_line}${new_line}Введите диапазон страниц для обработки:"

	msg_dpi_title="Разрешение в DPI"
	msg_dpi="Преобразование \"${file_name}\". Установить разрешение в DPI (по умолчанию 150):"

	msg_options_title="Параметры"
	msg_options="Выбор параметров для конвертации \"${file_name}\""
	msg_options_color="Генерировать цветной файл PPM"
	msg_options_gray="Генерировать файл серых оттенков PGM"
	msg_options_mono="Генерировать монохромный файл PBM"

	msg_images_root_name_title="Вставить префикс изображений"
	msg_images_root_name="Примечание: Названия изображений будут присваиваться с помощью префикса, за которым следуют числа в прогрессии (${file_name}-000.ppm, ${file_name}-001.ppm ...). Измените префикс для изображений или оставить значение по умолчанию:"

	msg_dest_dir="${base_file_name} (изображения)"
	msg_create_dir_error="Невозможно создать каталог назначения для изображений!"
}

load_language () {
	## Load localized strings AFTER english strings
	## - if localized strings not found use english for default
	## - if localized strings are incomplete use english only fot missing strings :-)
	load_language_en && [ "${lang}" != "en" ] && load_language_${lang}
}

lang=${LANGUAGE%%:*}
type load_language_${lang} > /dev/null || lang='en'
load_language

################################################################################

help () {
	echo
	echo "USE:\t\t${0##*/} pages files"
	echo
	echo "pages:\t\tallpages, selectpages"
	echo "files:\t\tfile1 file2 ..."
	echo
	echo "example:\t${0##*/} allpages /home/user/file1.pdf /home/user/file2.pdf"
	echo
	exit 0
}

checkIfProtected () {
	is_protected=$("${pdfinfo_bin}" "${1}" 2>&1 | sed "s/.*Incorrect password.*/Encrypted: yes/" | grep '^Encrypted:' | sed "s/^[^ ]* *\([^ ]*\).*/\1/")
}

askPassword () {
	password=$("${kdialog_bin}" --title "${msg_insert_password_title}" --password "${msg_insert_password_usr}") || exit 0
	password=$(echo ${password} |grep '^.' |sed 's/^/-upw /')

	if [ -z "${password}" ]; then
		password=$("${kdialog_bin}" --title "${msg_insert_password_title}" --password "${msg_insert_password_own}") || exit 0
		password=$(echo ${password} |grep '^.' |sed 's/^/-opw /')
	fi

	[ -z "${password}" ] && password=''
}

askRange () {
	range=$("${kdialog_bin}" --title "${msg_input_pages_range_title}" --inputbox "${msg_input_pages_range}" "1-") || exit 0
	range=$(echo "${range}" | sed 's/[[:blank:]]*//g' | sed 's/-end//' | sed 's/\(^[0-9][0-9]*\)/-f \1/' | sed 's/\(^-f [0-9][0-9]*\)-\([0-9][0-9]*\)/\1 -l \2/' | sed 's/^-\([0-9][0-9]*\)/-l \1/')
}

selectpages () {
	checkIfProtected "${1}"

	[ ${is_protected} = 'yes' ] && askPassword

	[ -z "${range}" ] && askRange || range=''

	options=$("${kdialog_bin}" --title "${msg_options_title}" --radiolist "${msg_options}" _color "${msg_options_color}" on _gray "${msg_options_gray}" off _mono "${msg_options_mono}" off --separate-output | sed 's/_color//' | sed 'y/_/-/')
	dpi=$("${kdialog_bin}" --title "${msg_dpi_title}" --inputbox "${msg_dpi}" "300" | grep [0-9] | grep -v [^0-9] | sed 's/^/-r /')

	while [ $# -ne 0 ]; do
		work_dir="${1%/*}"; [ ! -d "${work_dir}" ] && work_dir="$(pwd)"
		file_name="${1##*/}"
		base_file_name="${file_name%.*}"

		## Reload language strings with current variables
		load_language

		mkdir -p "${msg_dest_dir}" || ( "${kdialog_bin}" --error "${msg_create_dir_error}" && exit 3)

		images_root_name="img"
		#images_root_name=$("${kdialog_bin}" --title "${msg_images_root_name_title}" --inputbox "${msg_images_root_name}" "${base_file_name}")

		[ ! -f "${work_dir}/${file_name}" ] && shift && "${kdialog_bin}" --title "${msg_common_finish_title}" --passivepopup "${msg_common_file_not_found}" 5 && continue

		msg=$("${pdftoppm_bin}" ${password} ${options} ${dpi} ${range} "${work_dir}/${file_name}" "${msg_dest_dir}/${images_root_name}" 2>&1) && \
		"${kdialog_bin}" --icon image-x-generic --title "${msg_common_finish_title}" --passivepopup "${msg_common_finish_ok}" 5 || \
		{ "${kdialog_bin}" --title "${msg_common_finish_title}" --detailederror "${msg_common_finish_error}" "${msg}"; exit 2; }

		shift
	done
}

allpages () {
	range='all'
	selectpages "${@}"
}

################################################################################

[ "${1}" = "-h" ] || [ "${1}" = "--help" ] || [ ${#} -lt 2 ] && help

kdialog_bin=$(which kdialog)
[ -z "${kdialog_bin}" ] && echo "kdialog not found!" && exit 1

pdfinfo_bin=$(which pdfinfo)
[ -z "${pdfinfo_bin}" ] && "${kdialog_bin}" --title "${msg_common_software_not_found_title}" --error "${msg_common_pdfinfo_not_found_text}" && exit 2

pdftoppm_bin=$(which pdftoppm)
[ -z "${pdftoppm_bin}" ] && "${kdialog_bin}" --title "${msg_common_software_not_found_title}" --error "${msg_common_pdftoppm_not_found_text}" && exit 2

action="${1}"
shift

type "${action}" >/dev/null 2>&1 || \
	{ "${kdialog_bin}" --title "${msg_common_software_not_found_title}" --error "${msg_common_action_not_found_text}" && exit 3; }

"${action}" "${@}"

exit 0
