#! /bin/sh
#
# 	Part of kde-service-menu-pdf Version 1.0
# 	Copyright (C) 2007-2018 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/>.
#

if [ ${#} -eq 0 ] || [ "${1}" = "-h" ] || [ "${1}" = "--help" ]; then
	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
fi

action="${1}"
shift

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

load_language_de () {
	msg_alert_gs_not_found_title="Komponente wurde nicht gefunden"
	msg_alert_gs_not_found_text="Die gs Software wurde nicht gefunden! Bitte installieren Sie Ghostscript."

	msg_alert_pdftohtml_not_found_title="Komponente wurde nicht gefunden"
	msg_alert_pdftohtml_not_found_text="Die pdftohtml Software wurde nicht gefunden! Bitte installieren Sie pdftohtml"

	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="Beachte: Das Schlüsselwort \"end\" kann für die letzte Seite benutzt werden, anstatt deren Seitenzahl anzugeben. Bitte Seitenbereich von \"${file_name}\" angeben, der umgewandelt werden soll:"

	msg_options_title="Eigenschaften"
	msg_options="Optionen für die Umwandlung von \"${file_name}\" auswählen"
	msg_options_replace_links=".pdf Links mit .html vertauschen"
	msg_options_no_images="Bilder ignorieren"
	msg_options_no_frames="Keine Rahmen erstellen (Alles auf einer Seite)"
	msg_options_force_hidden_text="Versteckten Text mit herausziehen"
	msg_options_no_merge="Abschnitte nicht zusammensetzen"
	msg_options_no_drm="DRM-Einstellungen (Digital Restrictions Management) des Dokumentes überschreiben"

	msg_alert_overwrite_title="Alles überschreiben?"
	msg_alert_overwrite_text="Eine oder mehrere Zieldateien existieren! Alles überschreiben?"
	msg_save_file_title="Dokument speichern"

	msg_finish_title="Konvertierung des Dokuments \"${file_name}\""
	msg_finish_ok="Fertig."
	msg_finish_error="Ein Fehler ist aufgetreten."
	msg_file_not_found="Datei nicht gefunden."
}

load_language_en () {
	msg_alert_gs_not_found_title="Component not found"
	msg_alert_gs_not_found_text="Software gs not found! Please, install Ghostscript."

	msg_alert_pdftohtml_not_found_title="Component not found"
	msg_alert_pdftohtml_not_found_text="Software pdftohtml not found! Please, install it."

	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="Notes: The keyword \"end\" may be used to reference the final page of a document instead of a page number. Please input page range to convert from \"${file_name}\":"

	msg_options_title="Preferences"
	msg_options="Select options for conversion of \"${file_name}\""
	msg_options_replace_links="Excange .pdf links with .html"
	msg_options_no_images="Ignore images"
	msg_options_no_frames="Generate no frames (all in one page)"
	msg_options_force_hidden_text="Force hidden text extraction"
	msg_options_no_merge="Do not merge paragraphs"
	msg_options_no_drm="Override document DRM (Digital Restrictions Management) setting"

	msg_alert_overwrite_title="Overwrite all?"
	msg_alert_overwrite_text="One or more destination files exist! Overwrite all?"
	msg_save_file_title="Save document"

	msg_finish_title="Conversion of document \"${file_name}\""
	msg_finish_ok="Done."
	msg_finish_error="An error has occurred."
	msg_file_not_found="File not found."
}

load_language_fr () {
	msg_alert_gs_not_found_title="Composant non trouvé"
	msg_alert_gs_not_found_text="Logiciel Ghostscript non trouvé! S'il vous plaît, installez-le."

	msg_alert_pdftohtml_not_found_title="Composant non trouvé"
	msg_alert_pdftohtml_not_found_text="Logiciel pdftohtml non trouvé! S'il vous plaît, installez-le."

	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="Notes: Le mot \"end\" peut être utilisé pour désigner la dernière page.
Pour désigner toute une plage de pages, inscrivez le numéro de la première et de la dernière page de cette plage séparés par un \"-\".
Pour désigner une page isolée inscrivez son numéro séparé par un espace.
Pour désigner une seule page, entrez seulement le numéro de cette page.

  Ex:
    de la page 4 à la dernière page:
      4-end
    la page 2, de la page 4 à la page 7, et la page 9:
      2 4-7 9
    seulement la page 3:
      3

Saisissez les pages de \"${file_name}\" à convertir en HTML:"

	msg_options_title="Préferences"
	msg_options="Choisissez les options de conversion pour \"${file_name}\""
	msg_options_replace_links="Changer les liens .pdf en .html"
	msg_options_no_images="Ignorer les images"
	msg_options_no_frames="Ne pas générer de cadres (tout dans une seule page)"
	msg_options_force_hidden_text="Forcer l'extraction de textes cachés"
	msg_options_no_merge="Ne pas fusionner les paragraphes"
	msg_options_no_drm="Ne pas retranscrire les DRM (Digital Restrictions Management)"

	msg_alert_overwrite_title="Tout écraser?"
	msg_alert_overwrite_text="Un ou plusieurs fichiers de destination existe! Tout écraser?"
	msg_save_file_title="Sauver le document"

	msg_finish_title="Conversion du document \"${file_name}\""
	msg_finish_ok="Terminée."
	msg_finish_error="Une erreur est survenue."
	msg_file_not_found="Fichier non trouvé."
}

load_language_it () {
	msg_alert_gs_not_found_title="Componente non trovato"
	msg_alert_gs_not_found_text="Il software gs non è stato trovato! Per favore installa Ghostscript."

	msg_alert_pdftohtml_not_found_title="Componente non trovato"
	msg_alert_pdftohtml_not_found_text="Il software pdftohtml non è stato trovato! Per favore, installalo."

	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 \"${file_name}\":"

	msg_input_pages_range_title="Selezione range"
	msg_input_pages_range="Nota: La parola chiave \"end\" può essere usata per indicare la pagina finale di un documento al posto di un valore numerico. Per favore inserisci il range di pagine da estrarre da \"${file_name}\":"

	msg_options_title="Preferenze"
	msg_options="Seleziona le opzioni per la conversione di \"${file_name}\""
	msg_options_replace_links="Sostituisci i collegamenti .pdf con .html"
	msg_options_no_images="Ignora le immagini"
	msg_options_no_frames="Non generare frames (tutto in una pagina)"
	msg_options_force_hidden_text="Forza l'estrazione del testo nascosto"
	msg_options_no_merge="Non unire i paragrafi"
	msg_options_no_drm="Ignora le impostazioni DRM (Digital Restrictions Management)"

	msg_alert_overwrite_title="Sovrascrivi tutti?"
	msg_alert_overwrite_text="Uno o più file destinazione esistono già! Sovrascriverli tutti?"
	msg_save_file_title="Salva documento"

	msg_finish_title="Conversione del documento \"${file_name}\""
	msg_finish_ok="Conclusa."
	msg_finish_error="Si è verificato un errore."
	msg_file_not_found="File non trovato."
}

load_language_ru () {
	msg_alert_gs_not_found_title="Компонент не найден"
	msg_alert_gs_not_found_text="Программное обеспечение gs не найдено! Установите Ghostscript."

	msg_alert_pdftohtml_not_found_title="Компонент не найден"
	msg_alert_pdftohtml_not_found_text="Программное обеспечение pdftohtml не найдено! Установите pdftohtml."

	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="Примечание: Ключевое слово \"end\" может использоваться, чтобы сослаться на заключительную страницу документа вместо номера страницы. Пожалуйста, вставьте диапазон страниц для преобразования из \"${file_name}\":"

	msg_options_title="Параметры"
	msg_options="Выбор параметров для конвертации \"${file_name}\""
	msg_options_replace_links="Заменить ссылки с .pdf на .html"
	msg_options_no_images="Игнорировать изображения"
	msg_options_no_frames="Исключить создание кадров (все на одной странице)"
	msg_options_force_hidden_text="Принудительно извлекать скрытый текст"
	msg_options_no_merge="Не объединять абзацы"
	msg_options_no_drm="Переопределить настройки DRM документа (технические средства защиты авторских прав)"

	msg_alert_overwrite_title="Перезаписать все?"
	msg_alert_overwrite_text="Один или несколько файлов назначения существуют! Перезаписать все?"
	msg_save_file_title="Сохранить документ"

	msg_finish_title="Преобразование документа \"${file_name}\""
	msg_finish_ok="Готово."
	msg_finish_error="Произошла ошибка."
	msg_file_not_found="Файл не найден."
}

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

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

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

gs_bin=$(which gs)
[ -z "${gs_bin}" ] && "${kdialog_bin}" --title "${msg_alert_gs_not_found_title}" --icon configure --error "${msg_alert_gs_not_found_text}" && exit 2

pdftohtml_bin=$(which pdftohtml)
[ -z "${pdftohtml_bin}" ] && "${kdialog_bin}" --title "${msg_alert_pdftohtml_not_found_title}" --icon configure --error "${msg_alert_pdftohtml_not_found_text}" && exit 2

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

checkIfProtected () {
	output=$("${gs_bin}" -dBATCH -sNODISPLAY "${1}" 2>&1)
	gsexit=$?

	if [ "$gsexit" = "0" ]; then
		is_protected=0;
	else
		found=$(echo "$output" | grep -o "This file requires a password")
		if [ -n "$found" ]; then
			is_protected=1;
		else
			"${kdialog_bin}" --title "${msg_finish_title}" --passivepopup "${msg_finish_error}" 5
			exit $gsexit
		fi
	fi
}

selectpages () {
	checkIfProtected $1

	if [ ${is_protected} = 1 ]; then
		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=''
	fi

	if [ -z "${range}" ]; then
		range=$("${kdialog_bin}" --title "${msg_input_pages_range_title}" --icon edit-copy --inputbox "${msg_input_pages_range}" "1-end") || 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/')
	else
		range=''
	fi

	options=$("${kdialog_bin}" --title "${msg_options_title}" --icon configure --checklist "${msg_options}" _p "${msg_options_replace_links}" on _i "${msg_options_no_images}" off _noframes "${msg_options_no_frames}" on _hidden "${msg_options_force_hidden_text}" off _nomerge "${msg_options_no_merge}" off _nodrm "${msg_options_no_drm}" on --separate-output) || exit
	options=$(echo ${options} | sed 'y/_/-/')

	if [ $# -gt 1 ]; then
		multi_selection="true"
	else
		unset multi_selection
	fi

	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

		output_file_name="${work_dir}/${base_file_name}.html"
		if [ -e "${output_file_name}" ]; then
			if [ "$multi_selection" ]; then			# if you selected multiple files
				if [ ! "${overwrite_all}" ]; then		# if ${overwrite_all} is unset
					"${kdialog_bin}" --title "${msg_alert_overwrite_title}" --icon document-save-all --yesnocancel "${msg_alert_overwrite_text}"
					case "$?" in
						0)	overwrite_all="true";;		# click on Yes
						1)	overwrite_all="false";;		# click on No
						2)	exit 0;;					# click on Cancel
						esac
				fi
				if [ "${overwrite_all}" = "false" ]; then
					output_file_name=$("${kdialog_bin}" --title "${msg_save_file_title}" --icon document-save --getsavefilename "${output_file_name}" text/html) || exit 0
				fi
			else
				output_file_name=$("${kdialog_bin}" --title "${msg_save_file_title}" --icon document-save --getsavefilename "${output_file_name}" text/html) || exit 0
			fi
		fi

		[ ! -f "${work_dir}/${file_name}" ] && shift && "${kdialog_bin}" --title "${msg_finish_title}" --passivepopup "${msg_file_not_found}" 5 && continue
		"${pdftohtml_bin}" ${options} ${password} ${range} "${work_dir}/${file_name}" "${output_file_name}" && \
		"${kdialog_bin}" --title "${msg_finish_title}" --passivepopup "${msg_finish_ok}" 5 || \
		"${kdialog_bin}" --title "${msg_finish_title}" --passivepopup "${msg_finish_error}" 5

		shift
	done
}

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

#### main

"${action}" "${@}" && exit 0
