#!/usr/bin/bash
# Instala el certificado de Autofirma en los almacenes de Mozilla Firefox
#
# Con el parámetro -all recorre todos los directorios de usuario y funciona silenciosamente
# Sin parámetros, sólo instala el certificado en el directorio del usuario que lanza este script
# GECOS Team https://github.com/gecos-team/autofirma-gecos/blob/master/sources/usr/bin/AutoFirma-Firefox
# dnie-configurador
# Copyright (C) 2010 Alejandro Vargas
# Copyright (C) 2012 Daniel Calviño Sánchez
# Copyright (C) 2014 Daniel Calviño Sánchez
# Copyright (C) 2020-2025 Jóse Alberto Valle Cid
#
# 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/>.

readonly INSTALL_CERTIFICATES_SUCCESS=0
readonly INSTALL_CERTIFICATES_ERROR=1
function certinstall
{
	local workdir=$1
	local certdbN=$2
	local certtype=$3
	local configurationErrors=false
	for certdb in $(find $workdir -maxdepth 2 -name "$certdbN")
	do
		certdir=$(dirname ${certdb})
		uninstallOnepinCryptographicModule ${certdir}
		installCryptographicModule ${certdir}
		chmod a+rw ${certdir}/pkcs11.txt
		certutil -A -n "SocketAutoFirma" -t "C,," -i /usr/share/autofirma/AutoFirma_ROOT.cer -d ${certtype}:${certdir} || configurationErrors=true
		
		echo "Instalando certificados"
		pushd /usr/share/DNIe-certs
	    certutil -A -n "Autoridad de Certificación Raíz del DNIe" -i ACRAIZ-SHA2.cer -t CT,C,C -d ${certtype}:${certdir} || configurationErrors=true
	    certutil -A -n "Autoridad de Certificación Subordinada del DNIe 001" -i "ACDNIE001-SHA2.crt" -t CT,C,C -d ${certtype}:${certdir} || configurationErrors=true
	    certutil -A -n "Autoridad de Certificación Subordinada del DNIe 002" -i "ACDNIE002-SHA2.crt" -t CT,C,C -d ${certtype}:${certdir} || configurationErrors=true
	    certutil -A -n "Autoridad de Certificación Subordinada del DNIe 003" -i "ACDNIE003-SHA2.crt" -t CT,C,C -d ${certtype}:${certdir} || configurationErrors=true
	    certutil -A -n "Autoridad de Certificación Subordinada del DNIe 004" -i "AC DNIE 004.crt" -t CT,C,C -d ${certtype}:${certdir} || configurationErrors=true
	    certutil -A -n "Autoridad de Certificación Subordinada del DNIe 005" -i "AC DNIE 005.crt" -t CT,C,C -d ${certtype}:${certdir} || configurationErrors=true
	    certutil -A -n "Autoridad de Certificación Subordinada del DNIe 006" -i "AC DNIE 006.crt" -t CT,C,C -d ${certtype}:${certdir} || configurationErrors=true
	
	    certutil -A -n "Certificado Raíz de la Administración Pública de España" -i ACRAIZAPE.crt -t CT,C,c -d ${certtype}:${certdir} || configurationErrors=true
	    certutil -A -n "Certificado Raíz de la Fábrica Nacional de Moneda y Timbre de España" -i ACRAIZFNMTRCM.crt -t CT,C,c -d ${certtype}:${certdir} || configurationErrors=true
	    certutil -A -n "Certificado Raíz de la Fábrica Nacional de Moneda y Timbre de España RSA512" -i ACRAIZFNMTRCMSHA512.crt -t CT,C,c -d ${certtype}:${certdir} || configurationErrors=true
	    certutil -A -n "Certificado Raíz de la Fábrica Nacional de Moneda y Timbre de España SHA2" -i ACRAIZFNMTRCMSHA2.crt -t CT,C,c -d ${certtype}:${certdir} || configurationErrors=true
	
	    certutil -A -n "Certificado Raíz de la Fábrica Nacional de Moneda y Timbre de España Clase2 CA" -i FNMTClase2CA.cer -t CT,C,c -d ${certtype}:${certdir} || configurationErrors=true
	    popd
	
	    if $configurationErrors; then
	        # TODO Provide better information about the errors
	        installCertificatesLog="Certificados: algunos certificados no se pudieron instalar (ERROR)."
	
	        return $INSTALL_CERTIFICATES_ERROR
	    fi
	
	    installCertificatesLog="Certificados instalados: AutoFirma ACRAIZ-SHA2, ACDNIE001-SHA2, ACDNIE002-SHA2, ACDNIE003-SHA2, ACDNIE004, ACDNIE005, ACDNIE006, ACRAIZAPE, ACRAIZFNMTRCM, ACRAIZFNMTRCMSHA512, ACRAIZFNMTRCMSHA2 y FNMTClase2CA (CORRECTO)."
	done
	return $INSTALL_CERTIFICATES_SUCCESS
}
function certuninstall
{
	local workdir=$1
	local certdbN=$2
	local certtype=$3
	for certdb in $(find $workdir -maxdepth 2 -name "$certdbN")
	do
		certdir=$(dirname ${certdb})
		echo "Eliminando el certificados en el directorio" $certdir
	    certutil -D -n "SocketAutoFirma" -d $certtype:${certdir} > /dev/null 2>&1
	    certutil -D -n "Autoridad de Certificación Raíz del DNIe" -d $certtype:${certdir} > /dev/null 2>&1
		certutil -D -n "Autoridad de Certificación Subordinada del DNIe 001" -d $certtype:${certdir} > /dev/null 2>&1
		certutil -D -n "Autoridad de Certificación Subordinada del DNIe 002" -d $certtype:${certdir} > /dev/null 2>&1
		certutil -D -n "Autoridad de Certificación Subordinada del DNIe 003" -d $certtype:${certdir} > /dev/null 2>&1
		certutil -D -n "Autoridad de Certificación Subordinada del DNIe 004" -d $certtype:${certdir} > /dev/null 2>&1
		certutil -D -n "Autoridad de Certificación Subordinada del DNIe 005" -d $certtype:${certdir} > /dev/null 2>&1
		certutil -D -n "Autoridad de Certificación Subordinada del DNIe 006" -d $certtype:${certdir} > /dev/null 2>&1
		certutil -D -n "Certificado Raíz de la Administración Pública de España" -d $certtype:${certdir} > /dev/null 2>&1
		certutil -D -n "Certificado Raíz de la Fábrica Nacional de Moneda y Timbre de España" -d $certtype:${certdir} > /dev/null 2>&1
		certutil -D -n "Certificado Raíz de la Fábrica Nacional de Moneda y Timbre de España RSA512" -d $certtype:${certdir} > /dev/null  2>&1
		certutil -D -n "Certificado Raíz de la Fábrica Nacional de Moneda y Timbre de España SHA2" -d $certtype:${certdir} > /dev/null 2>&1
	  done
}
detectDialogType() {
    if [ x"$KDE_FULL_SESSION" = x"true" ]; then
        local kdeRunning=true
    fi

    if [ -n "$kdeRunning" -a -x /usr/bin/kdialog ]; then
        dialogType="kdialog"
    elif [ -x /usr/bin/zenity ]; then
        dialogType="zenity"
    elif [ -x /usr/bin/kdialog ]; then
        dialogType="kdialog"
    elif [ -x /usr/bin/Xdialog ]; then
        dialogType="Xdialog"
    fi
}

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

# Shows a message to the user using a dialog, or printing a message in the
# console and waiting for Enter being pressed (depending on the environment).
# In non-interactive (auto) mode no dialog whatsoever is shown, only the message
# in the console. There is no need to press Enter in this case.
#
# First parameter: the text of the message
message() {
    local text=$1

    if [ -z "$DISPLAY" -o -z "$dialogType" ]; then
        echo -e "$text"
        test "$TERM" = "dumb" && return
        [ $auto = 1 ] && return
		echo "Presione Intro para continuar"
		read
        return
    fi

    if [ $dialogType = "kdialog" ]; then
        /usr/bin/kdialog --msgbox "$text" || exit 1
    elif [ $dialogType = "zenity" ]; then
        /usr/bin/zenity --info  --text "$(echo -n "$text"|fold -c -s -w 100)" --no-wrap || exit 1
    elif [ $dialogType = "Xdialog" ]; then
        /usr/bin/Xdialog --msgbox "$text" || exit 1
    fi
}

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

# Shows a message to the user using a dialog, or printing a message in the
# console.
# The dialog contains a button to continue and a button to cancel (which exits
# the script). If the message is shown in the console, the script will wait
# until Enter is pressed (or the script aborted).
# In non-interactive (auto) mode no dialog whatsoever is shown, only the message
# in the console. There is no need to press Enter in this case.
#
# First parameter: the text of the message
messageContinueCancel() {
    local text=$1

    if [ -z "$DISPLAY" -o -z "$dialogType" ]; then
        echo -e "$text"
        test "$TERM" = "dumb" && return
        [ $auto = 1 ] && return
        echo "Presione Intro para continuar o CTRL+C para cancelar"
        read || exit 
        return
    fi

    if [ $dialogType = "kdialog" ]; then
        /usr/bin/kdialog --yesno "$text" || exit 1
    elif [ $dialogType = "zenity" ]; then
        /usr/bin/zenity --question   --text "$(echo -n "$text"|fold -c -s -w 100)" --ok-label "Continuar" --cancel-label "Cancelar"  --no-wrap|| exit 1
    elif [ $dialogType = "Xdialog" ]; then
        /usr/bin/Xdialog --yesno "$text" --ok-label "Continuar" --cancel-label "Cancelar" || exit 1
    fi
}

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

# Shows a warning to the user using a dialog, or printing a message in the
# console.
# The dialog contains a button to continue and a button to cancel (which exits
# the script). If the message is shown in the console, the script will wait
# until Enter is pressed (or the script aborted).
# In non-interactive (auto) mode no dialog whatsoever is shown, only the message
# in the console. After showing the message the script is aborted.
#
# First parameter: the text of the warning
warningContinueCancel() {
    local text=$1

    if [ -z "$DISPLAY" -o -z "$dialogType" ]; then
        echo -e "$text"
        test "$TERM" = "dumb" && exit 1
        [ $auto = 1 ] && return
        echo "Presione Intro para continuar o CTRL+C para cancelar"
        read || exit 
        return
    fi

    if [ "$dialogType" = "kdialog" ]; then
        /usr/bin/kdialog --warningcontinuecancel "$text" || exit 
    elif [ "$dialogType" = "zenity" ]; then
        /usr/bin/zenity --question  --text "$(echo -n "$text"|fold -c -s -w 100)" --ok-label "Continuar" --cancel-label "Cancelar" --no-wrap|| exit 
    elif [ "$dialogType" = "Xdialog" ]; then
        /usr/bin/Xdialog --yesno "$text" --ok-label "Continuar" --cancel-label "Cancelar" || exit 
    fi
}

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

# Checks that pcscd is installed in the system and, if its version is older than
# 1.6.0, warns the user to manually check that the service is started at boot.
#
# Returns: WARNING if some problem was detected, SUCCESS otherwise
readonly CHECK_PCSCD_SUCCESS=0
readonly CHECK_PCSCD_WARNING=1
checkPcscd() {
    checkPcscdLog="pcscd:"

    if [ ! -f /usr/sbin/pcscd ]; then
        warningContinueCancel "No se encontró el servicio 'pcscd' (que es el encargado de acceder a su lector de tarjetas). Tenga en cuenta que dicho servicio es imprescindible para usar su DNI electrónico, por lo que deberá instalarlo usted mismo si no lo estuviese ya (podría ocurrir que ya lo tuviese instalado, aunque en una ruta distinta a '/usr/sbin/pcscd' que fue en la que se buscó)."

        checkPcscdLog="$checkPcscdLog no se encontró pcscd; verifique que está instalado o, sino, instálelo (PROBLEMA)\n"

        return $CHECK_PCSCD_WARNING
    fi

    local pcscdVersion=$(/usr/sbin/pcscd -v | grep version | sed -e "s/.*version \(.*\)/\1/")
    if [ $pcscdVersion = "1.6.0" -o `echo -e "$pcscdVersion\n1.6.0" | sort --version-sort | head --lines=1` != "1.6.0" ]; then
        warningContinueCancel "Se encontró el servicio 'pcscd' (que es el encargado de acceder a su lector de tarjetas), aunque una versión anterior a la 1.6.0. A partir de la versión 1.6.0 el servicio arranca automáticamente cuando se le necesita, pero en versiones anteriores, como la encontrada, debe asegurarse que está en funcionamiento cuando lo vaya a utilizar. Si no lo estuviese ya, por favor, configure su sistema para que el servicio 'pcscd' se arranque al inicio."

        checkPcscdLog="$checkPcscdLog se encontró pcscd < 1.6.0; verifique que se arranca en el inicio del sistema (AVISO)\n"

        return $CHECK_PCSCD_WARNING
    fi

    # pcscd >= 1.6.0 starts automatically when needed, as explained in
    # http://ludovicrousseau.blogspot.com.es/2010/09/pcscd-auto-start.html,
    # so no configuration is needed

    checkPcscdLog="$checkPcscdLog se encontró pcscd >= 1.6.0 (CORRECTO)\n"

    return $CHECK_PCSCD_SUCCESS
}

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

# Checks if there is access to the pages that the certificates will be
# downloaded from.
# If there is no access a warning will be shown to the user to check his
# Internet connection. The warning will be shown again if the user tries to
# continue but there is still no access to the page.
checkAccess() {
    local site=""
    for site in www.dnielectronico.es www.cert.fnmt.es; do
        echo "Probando si se puede acceder a $site";
        while ! wget --quiet --output-document=/dev/null $site; do
            warningContinueCancel "No se pudo acceder a '$site'. Por favor, compruebe que tiene conexión a Internet. Si está seguro de tener conexión pero aún así no se puede acceder a la página puede que dicha página esté caída en estos momentos. En ese caso, cancele y ejecute el configurador de nuevo más tarde para volver a intentarlo."
        done
    done
}

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

# Checks if the "Estonian ID Card PKCS11 module loader" Mozilla extension is
# installed system wide (it is not checked for user specific installations; it
# is assumed that someone willing to use the Spanish DNI will have that
# extension installed only from a default distribution package) and, if it is,
# shows a warning to the user to uninstall the extension.
# The warning will be shown again if the user tries to continue without
# uninstalling the extension.
ensureEstonianIdCardPKCS11ModuleLoaderExtensionIsNotInstalled() {
    local isInstalled=true
    #No hacemos nada si el folder no existe
    if [ -d /usr/share/mozilla/extensions ] ; then
	    while $isInstalled; do
	        local extensionSystemDirectory=`find "/usr/share/mozilla/extensions" -name "{aa84ce40-4253-a00a-8cd6-0800200f9a66}"`
	
	        if [ $? = 0 ] && [ -n "$extensionSystemDirectory" ]; then
	            warningContinueCancel "Debe desinstalar la extensión de Mozilla «Estonian ID Card PKCS11 module loader» («Cargador del módulo criptográfico del \"DNI de Estonia\"») para continuar con la configuración, ya que el módulo criptográfico «onepin-opensc-pkcs11» usado por el DNI de Estonia causa problemas con el DNI electrónico español en Firefox. El módulo en sí será eliminado de Firefox por este configurador, pero la extensión lo cargaría de nuevo cada vez que lo arrancase, así que debe desinstalar dicha extensión. Si no puede o no quiere desinstalarla ahora, cancele y ejecute el configurador de nuevo más tarde cuando ya la haya desinstalado.\n\nNota: en Mageia, dicha extensión pertenece al paquete «mozilla-esteid». Desinstale dicho paquete para desinstalar la extensión."
	        else
	            isInstalled=false
	        fi
	    done
	 else
		isInstalled=false
	 fi
}

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

# Checks if the given application is running and, if it is, shows a warning to
# the user to close the application.
# The warning will be shown again if the user tries to continue without closing
# the application.
#
# First parameter: process name of the application to check.
# Second parameter: name of the application to be shown in the warning.
ensureApplicationIsNotRunning() {
    local applicationProcessName=$1
    local applicationName=$2

    test $EUID = "0" && local selectAllProcess="a"

    local isRunning=true
    while $isRunning; do
        local applicationProcessCount=`ps x$selectAllProcess | grep "$applicationProcessName" | grep -v "grep" | wc -l`

        if [ $applicationProcessCount -gt 0 ]; then
            warningContinueCancel "Debe cerrar $applicationName para continuar con la configuración. Si no puede o no quiere cerrarlo ahora, cancele y ejecute el configurador de nuevo más tarde cuando ya lo haya cerrado."
        else
            isRunning=false
        fi
    done
}

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

# Ensures that Firefox is not running through ensureApplicationIsNotRunning
# function.
ensureFirefoxIsNotRunning() {
    ensureApplicationIsNotRunning "firefox" "Firefox"
}

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

# Ensures that Thunderbird is not running through ensureApplicationIsNotRunning
# function.
ensureThunderbirdIsNotRunning() {
    ensureApplicationIsNotRunning "thunderbird" "Thunderbird"
}

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

# Downloads the given certificate to /usr/share/DNIe-certs.
# If the certificate can not be downloaded a warning will be shown to the user
# to check his Internet connection. The warning will be shown again if the user
# tries to continue but the certificate still can not be downloaded.
#
# First parameter: the URL of the certificate to download
# Second parameter (optional): the name of the file to download the certificate
#     to. If not set, the name of the file will be the basename of the URL (that
#     is, everything after the last '/').
downloadCertificate() {
    local url=$1
    local filename=`basename $url`

    if [ -n "$2" ]; then
        filename=$2
    fi

    # wget refuses to download a file if it needs HTTPS (either directly or by
    # redirection) and it can not verify the certificate of the URL. As the
    # certificate of the FNMT itself has to be downloaded by accessing the HTTPS
    # web of the FNMT, the certificate verification of wget must be disabled in
    # order to download it.
    while ! wget --no-check-certificate --quiet --output-document="/usr/share/DNIe-certs/$filename" $url --user-agent="Mozilla/5.0 (X11; Linux i686; rv:73.0) Gecko/20100101 Firefox/73.0"; do
        warningContinueCancel "No se pudo descargar el certificado '$url'. Por favor, compruebe que tiene conexión a Internet. Si está seguro de tener conexión pero aún así no se puede descargar el certificado puede que la página que lo aloja esté caída en estos momentos. En ese caso, cancele y ejecute el configurador de nuevo más tarde para volver a intentarlo."
    done
}

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

# Downloads all the needed certificates.
# This function will not return until all the certificates were successfully
# downloaded (or the user aborted the script).
downloadCertificates() {
	#Only download when run as root, i keep the certificates
	if [ $EUID = 0 ]; then
	    pushd /usr/share/DNIe-certs
	    echo "Descargando certificados de la Dirección General de la Policía"
	    if [ -n "$(ls /usr/share/DNIe-certs)" ]; then
			rm -f /usr/share/DNIe-certs/*
		fi
	    #downloadCertificate https://www.dnielectronico.es/ZIP/ACRAIZ-SHA2.CAB
	    downloadCertificate https://www.dnielectronico.es/ZIP/ACRAIZ-SHA2.zip
	    downloadCertificate https://www.dnielectronico.es/ZIP/ACDNIE001-SHA2.zip
	    downloadCertificate https://www.dnielectronico.es/ZIP/ACDNIE002-SHA2.zip
	    downloadCertificate https://www.dnielectronico.es/ZIP/ACDNIE003-SHA2.zip
	    downloadCertificate https://www.dnielectronico.es/ZIP/ACDNIE004.zip
	    downloadCertificate https://www.dnielectronico.es/ZIP/ACDNIE005.zip
	    downloadCertificate https://www.dnielectronico.es/ZIP/ACDNIE006.zip
	
	    echo "Descargando certificados de la Fábrica Nacional de Moneda y Timbre"
	
	    downloadCertificate http://www.cert.fnmt.es/certs/ACRAIZAPE.crt
	    downloadCertificate http://www.cert.fnmt.es/certs/ACRAIZFNMTRCM.crt
	    downloadCertificate http://www.cert.fnmt.es/certs/ACRAIZFNMTRCMSHA512.crt
	    downloadCertificate http://www.cert.fnmt.es/certs/ACRAIZFNMTRCMSHA2.crt
	    downloadCertificate https://www.sede.fnmt.gob.es/documents/10445900/10526749/FNMTClase2CA.cer
			#cabextract ACRAIZ-SHA2.CAB 
			unzip -o ACRAIZ-SHA2.zip
			unzip -o ACDNIE001-SHA2.zip 
			unzip -o ACDNIE002-SHA2.zip
			unzip -o ACDNIE003-SHA2.zip
			unzip -o ACDNIE004.zip
			unzip -o ACDNIE005.zip
			unzip -o ACDNIE006.zip
			rm -rf *.{CAB,zip}
		popd
    fi
}

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

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

# Check the onepin-opensc-pkcs11 cryptographic module from the specified
# Mozilla profile.
#
# As firefox not longer uses secmod.db is all what I can do right now
#
# First parameter: the directory of the profile to check the module from.
# Returns: SUCCESS if the module was not installed), ERROR if some error happened.
readonly UNINSTALL_ONEPIN_CRYPTOGRAPHIC_MODULE_SUCCESS=0
readonly UNINSTALL_ONEPIN_CRYPTOGRAPHIC_MODULE_ERROR=1
uninstallOnepinCryptographicModule() {
    local securityDatabasesDirectory=$1
    
    #if [ -f "$securityDatabasesDirectory/secmod.db" ]; then
	    #echo "Desinstalando módulo criptográfico onepin-opensc-pkcs11"
	    echo "Revisando módulo criptográfico onepin-opensc-pkcs11"
	    if ! grep "/usr/lib$extraLib/onepin-opensc-pkcs11.so" "$securityDatabasesDirectory/pkcs11.txt" ; then
	        uninstallOnepinCryptographicModuleLog="El módulo criptográfico onepin-opensc-pkcs11 no estaba instalado (CORRECTO)."
	        return $UNINSTALL_ONEPIN_CRYPTOGRAPHIC_MODULE_SUCCESS
	    else
	    #local date=`date "+%Y%m%d-%H:%M:%S"`
	    #mvOutput=`mv -f "$securityDatabasesDirectory/secmod.db" "$securityDatabasesDirectory/secmod.db.bak-$date" 2>&1`
	    #if [ $? -ne 0 ]; then
	        uninstallOnepinCryptographicModuleLog="Debe quitar el módulo criptográfico onepin-opensc-pkcs11.so de $securityDatabasesDirectory/pkcs11.txt: (ERROR)"
	        return $UNINSTALL_ONEPIN_CRYPTOGRAPHIC_MODULE_ERROR
	    fi
	
	    #uninstallOnepinCryptographicModuleLog="Módulo criptográfico onepin-opensc-pkcs11.so desinstalado correctamente; archivo secmod.db original renombrado como secmod.db.bak-$date (CORRECTO)."
	    #return $UNINSTALL_ONEPIN_CRYPTOGRAPHIC_MODULE_SUCCESS
	 #fi
}

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

# Adds the opensc-pkcs11 cryptographic module to the specified Mozilla profile.
#
# First parameter: the directory of the profile to install the module to.
# Returns: SUCCESS if the module was successfully installed (or if it was
# already installed), ERROR if some error happened.
readonly INSTALL_CRYPTOGRAPHIC_MODULE_SUCCESS=0
readonly INSTALL_CRYPTOGRAPHIC_MODULE_ERROR=1
installCryptographicModule() {
    local securityDatabasesDirectory=$1
    #if [ -f "$securityDatabasesDirectory/secmod.db" ]; then
	    echo "Instalando módulo criptográfico opensc-pkcs11"
	    if [ `modutil -list -dbdir "$securityDatabasesDirectory" | grep "/usr/lib$extraLib/opensc-pkcs11.so" | wc -l` -gt 0 ]; then
	        installCryptographicModuleLog="El módulo criptográfico opensc-pkcs11 ya estaba instalado (CORRECTO)."
	        return $INSTALL_CRYPTOGRAPHIC_MODULE_SUCCESS
	    fi
	
	    modutilOutput=`modutil -force -add "DNIe" -libfile "/usr/lib$extraLib/opensc-pkcs11.so" -dbdir "$securityDatabasesDirectory" 2>&1`
	    if [ $? -ne 0 ]; then
	        installCryptographicModuleLog="No se pudo instalar el módulo criptográfico opensc-pkcs11.so: $modutilOutput (ERROR)"
	        return $INSTALL_CRYPTOGRAPHIC_MODULE_ERROR
	    fi
	
	    installCryptographicModuleLog="Módulo criptográfico opensc-pkcs11.so instalado correctamente (CORRECTO)."
	    return $INSTALL_CRYPTOGRAPHIC_MODULE_SUCCESS
	 #fi
}

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

# Whether we are running in a i586 or x86_64 system
uname --machine | grep --quiet "64" && extraLib="64" || extraLib=""
certdbN="cert9.db"
certtype="sql"
auto=0

detectDialogType

# If the configurator is run with an active display a dialog tool is required.
# This is made to prevent the script to "hang" when waiting for the user to
# press enter when showing the greeting message, as if the script was launched
# with a double click the user will not be able to interact with the script. So
# if no dialog tool is found and there is an active display, the script just
# exits here.
if [ -z "$dialogType" -a -n "$DISPLAY" ]; then
    echo "Se necesita kdialog, zenity o Xdialog. Instale alguno de estos programas y luego ejecute de nuevo el configurador."
    exit 1
fi

case "$1" in
	"-all") 
		auto=1
		[ ! -d /usr/share/DNIe-certs ] && mkdir -p /usr/share/DNIe-certs
		#checkAccess
		#java -Djava.awt.headless=true -classpath \
		#/usr/share/autofirma/Configurador.jar:/usr/share/autofirma/autofirma.jar \
		#es.gob.afirma.standalone.configurator.AutoFirmaConfigurator
		java -Djava.awt.headless=true -jar /usr/share/autofirma/Configurador.jar
		mv -f /usr/share/autofirma/{Autofirma_ROOT,AutoFirma_ROOT}.cer
		#No usaremos estos scripts
		if [ -f "/usr/share/autofirma/script.sh" ]; then
			rm -f /usr/share/autofirma/*.sh
		fi
		mkdir -p /usr/share/DNIe-certs
		if downloadCertificates ; then
			message "Certificados descargados
Cada usuario los instalara al ejecutar la aplicacion"
			trust anchor --store /usr/share/autofirma/AutoFirma_ROOT.cer 2>/dev/null
		else 
			message "No se descargaron los Certificados
Vuelva a ejecutar dnie-configurador -all"
		fi
		foxdir=$(find /home/ -maxdepth 2 -name ".mozilla")
		for dir in $foxdir
		do
			rm -f $(echo $dir|cut -d '/' -f1-3)/.config/autofirma*
		  #if [ -d "$dir/firefox" ]; then
		     #certuninstall $dir/firefox $certdbN $certtype
		  #fi
		  #certutil -D -d sql:$(echo $dir|cut -d '/' -f1-3)/.pki/nssdb -n "SocketAutoFirma" 
		 done
		#thundir=$(find /home/ -maxdepth 2 -name ".thunderbird") 
		exit 0
		;;
	"-un")
		foxdir=$(find /home/ -maxdepth 2 -name ".mozilla")
		#thundir=$(find /home/ -maxdepth 2 -name ".thunderbird")
		for dir in $foxdir
		do
			rm -f $(echo $dir|cut -d '/' -f1-3)/.config/autofirma*
		  #if [ -d "$dir/firefox" ]; then
		     #certuninstall $dir/firefox $certdbN $certtype
		  #fi
		  #certutil -D -d sql:$(echo $dir|cut -d '/' -f1-3)/.pki/nssdb -n "SocketAutoFirma" 
		 done
		#for dir in $thundir
		#do
		  #certuninstall $dir $certdbN $certtype
		 #done
		 trust anchor --remove /usr/share/autofirma/AutoFirma_ROOT.cer 2>/dev/null
		 rm -rf /usr/share/DNIe-certs
		exit;;
	*) 
		foxdir=$(find $HOME/ -maxdepth 1 -name ".mozilla")
		thundir=$(find $HOME/ -maxdepth 1 -name ".thunderbird");;
esac


if [ -z "$foxdir" ] && [ -z "$thundir" ]; then
	message "
No se encontraron perfiles de firefox o thunderbird.
Si estan instalados ejecute alguno (o ambos) y posteriormente ejecute dnie-configurador
"
	exit 1
fi
if [ -z "$foxdir" ]; then
message "
No se encontraron perfiles de firefox, AutoFirma trabaja con la información de esos perfiles.
Si esta instalado ejecute firefox y posteriormente ejecute dnie-configurador
"
	exit 1
fi

messageContinueCancel "Este programa configura OpenSC-OpenDNIe e instala en Firefox y Thunderbird el módulo criptográfico para el DNIe y los certificados de la Dirección General de Policía y de la Fábrica Nacional de Moneda y Timbre.\nAdemás, debido a incompatibilidades con el DNI electrónico, en caso de encontrarse el módulo criptográfico «onepin-opensc-pkcs11» se desinstalará de Firefox y Thunderbird (aunque, debido a problemas con los applets de Java, para ello deberán desinstalarse todos los módulos criptográficos). Dicho módulo se usa principalmente en el DNI de Estonia, por lo que no debería ser un problema ;)\n\nTodos los certificados se descargarán directamente de Internet, así que asegúrese de estar conectado antes de continuar.\nAsegúrese además de que no tiene conectado el DNI electrónico, ya que esto ralentiza mucho el proceso de configuración."

pcscdAvailable=false
if checkPcscd; then
    pcscdAvailable=true
fi

ensureEstonianIdCardPKCS11ModuleLoaderExtensionIsNotInstalled

ensureFirefoxIsNotRunning
ensureThunderbirdIsNotRunning

configurationSummary=$configureAllUsersSummary
configurationLog=$configureAllUsersLog

for dir in $foxdir ; do
  Cuser="$(echo -n $dir|cut -d '/' -f3)"
  if [ -d "$dir/firefox" ]; then
	  echo "Actualizando el certificado de AutoFirma en el directorio" $dir
	  certuninstall $dir/firefox $certdbN $certtype
	  if certinstall $dir/firefox $certdbN $certtype ; then
		configureAllUsersSummary="$configureAllUsersSummary""Usuario $Cuser Perfil firefox
	\n$uninstallOnepinCryptographicModuleLog\n$installCryptographicModuleLog\n"
	  else
		messageContinueCancel "Usuario $Cuser Perfil firefox\n$installCertificatesLog"
	  fi
  fi
  #if [ ! -d "/home/$Cuser/.pki/nssdb" ]; then
	#mkdir -p "/home/$Cuser/.pki/nssdb"
  #fi
  touch /home/$Cuser/.config/autofirma
  #certutil -d sql:/home/$Cuser/.pki/nssdb -A -n "SocketAutoFirma" -i /usr/share/autofirma/AutoFirma_ROOT.cer -t "TCP,TCP,TCP" 
  #chown ${Cuser}:${Cuser} -R "/home/$Cuser/.pki"
  #chmod a+rwx -R "/home/$Cuser/.pki"
  #chmod a-x /home/$Cuser/.pki/nssdb/*
done
for dir in $thundir
do
  echo "Actualizando el certificado de AutoFirma en el directorio" $dir
  certuninstall $dir $certdbN $certtype
  if certinstall $dir $certdbN $certtype ; then
	configureAllUsersSummary="$configureAllUsersSummary""\nUsuario $(echo -n $dir|cut -d '/' -f3) Perfil thunderbird
\n$uninstallOnepinCryptographicModuleLog\n$installCryptographicModuleLog\n"
  else
	messageContinueCancel "Usuario $(echo -n $dir|cut -d '/' -f3) Perfil thunderbird\n$installCertificatesLog"
  fi
done
summary="Proceso de configuración terminado:\n\n"
if ! $pcscdAvailable; then
summary="$summary$checkPcscdLog\n"
fi
summary="$summary$configurationSummary"

messageContinueCancel "$summary\nSi lo desea, antes de salir del programa puede ver información detallada de la configuración realizada.\n"

message "$checkPcscdLog\n"
message "$configurationLog\n$configureAllUsersSummary\n$installCertificatesLog"

