#!/bin/bash
# -*- ENCODING: UTF-8 -*-

# postinst
#
# Clean and secures the operating system after installing packages.
#
# Copyright (c) 2013-2026: Alexis Puente Montiel   < pica (a) picalibre.org >
#
# Licensed according to GNU AGPL version 3.0.
#
# It is libre/free software; you can use, redistribute and/or modify it according to the terms of GNU AGPL as published by GNU, version 3.0, 19 November 2007.
#
# It is distributed in the hope that it will be useful, but without any warranty. Read GNU AGPL version 3.0 for additional details.
#
# A copy of GNU AGPL version 3.0 is available at /usr/share/doc/<software-package-name>/agpl-3.0.txt (additionally on Internet as text at https://www.gnu.org/licenses/agpl-3.0.txt and as HTML at https://www.gnu.org/licenses/agpl-3.0-standalone.html ).
#
# Note: Additionally to the official e-mails, picalibre.org is strictly the only official site for this software project, please consider using it to download, report bugs and contribute.
#
# Depends: apt, bash, coreutils, findutils, gawk | mawk | original-awk, grep, lsof, sed
# Recommends: 7zip | p7zip-full | unar | unzip, menu, pica-img, pica-man, sysvinit-utils (<<2.88dsf-59.3) | init-system-helpers, zip


### SCRIPT VARIABLES ########################################

CNAME="postinst"
VERSION="1.3.1"
TITLE="'postinst'"

# Translations
if [ "$LANG" = "" ] ; then export $(cat /etc/default/locale | grep -a 'LANG=') ; fi
TEXTDOMAIN=pica-skel
TEXTDOMAINDIR=/usr/share/locale/

# Write errors to log
ERRORLOG="$HOME/.${CNAME}.log"
if [ -e "$ERRORLOG" ] ; then
	mv -f $ERRORLOG ${ERRORLOG}.ant
fi
if [ -e "$ERRORLOG" ] ; then rm -rf "$ERRORLOG" ; fi

for i in /etc/pica-global.dist /etc/pica-global.orig /etc/pica-global /etc/pica-global.local ~/.pica-global ~/pica-global ; do
	if [ -f "$i" ] ; then
	cat "$i"
	source "$i"
	source <(cat $i | sed -e "s/=\(YES\|Yes\|yes\|y\|SÍ\|SI\|Sí\|Si\|sí\|si\|S\|s\)/=Y/g" -e "s/=\(No\|no\|n\)/=N/g" -e "s/=\"\(YES\|Yes\|yes\|y\|SÍ\|SI\|Sí\|Si\|sí\|si\|S\|s\)\"/=Y/g" -e "s/=\"\(No\|no\|n\)\"/=N/g")
	fi
done
if [ "$DEBUG" = "Y" ] ; then
	set -xv
	DEBUG="Y"
else
	ERRORLOG="/tmp/.${CNAME}_$(id -nu).log"
	if [ -e "$ERRORLOG" ] ; then mv -f $ERRORLOG ${ERRORLOG}.ant ; fi
	if [ -e "$ERRORLOG" ] ; then rm -rf "$ERRORLOG" ; fi
fi
#if [ "$DEBUG" = "" ] ; then DEBUG="N" ; fi
if [ "$DEBUG" != "N" ] ; then
exec > >(tee -a "$ERRORLOG") 2>&1
echo "$0" "$*" >> "$ERRORLOG"
echo "$CNAME" "$VERSION" >> "$ERRORLOG"
echo $(date +%Y-%m-%d_%H:%M:%S) $"Start" >> "$ERRORLOG"
echo "env:" >> "$ERRORLOG"
env >> "$ERRORLOG"
echo "set:" >> "$ERRORLOG"
set >> "$ERRORLOG"
#else
#exec 2>>"$ERRORLOG"
fi

# Description:
BDESCRIP=$"Clean and secures the operating system after installing packages."
LDESCRIP=$"$TITLE is a tool to clean and secure the operating system after installing packages."

# Documentation:
docu_info () {
echo "$CNAME ($VERSION) - $BDESCRIP"
echo 
echo $"Usage:" $CNAME [$"OPTIONS"]
echo 
echo $"Options:"
echo -e "$ODESCRIP"
echo 
echo $"'man $CNAME' for more information."
echo 
}
ODESCRIP=" -n""\t"$"Do not delete downloaded packages.""\n"" -k""\t"$"Do not delete old kernels.""\n"" -x""\t"$"Show help documentation.""\n\n"$"Default settings can be changed in /etc/pica-postinst""\n\n"$"Before finishing, it will execute in alphanumeric order every Bash script whose name ends in '.sh' that is inside /etc/pica-postinst.d/ (if any)."

cat /etc/pica-postinst.orig >> "$ERRORLOG"
source /etc/pica-postinst.orig
source <(cat /etc/pica-postinst.orig | sed -e "s/=\(YES\|Yes\|yes\|y\|SÍ\|SI\|Sí\|Si\|sí\|si\|S\|s\)/=Y/g" -e "s/=\(No\|no\|n\)/=N/g")
if [ -f /etc/pica-postinst ] ; then
cat /etc/pica-postinst >> "$ERRORLOG"
source /etc/pica-postinst
source <(cat /etc/pica-postinst | sed -e "s/=\(YES\|Yes\|yes\|y\|SÍ\|SI\|Sí\|Si\|sí\|si\|S\|s\)/=Y/g" -e "s/=\(No\|no\|n\)/=N/g")
fi

while getopts ankx OPTION ; do
	case $OPTION in
		a )   APT="N"    ;;
		n )   CLEAN="N"  ;;
		k )   KCLEAN="N" ;;
		x )   docu_info ; exit 0 ;;
	esac
done

if [ "$APT" = "" ] ; then
	if [ "$(lsof /var/lib/apt/lists/lock 2>>$ERRORLOG | grep -a -c ^)" -eq 0 ] && [ "$(lsof /var/lib/apt/lists/lock-frontend 2>>$ERRORLOG | grep -a -c ^)" -eq 0 ] && [ "$(lsof /var/lib/apt/lists/lock-frontened 2>>$ERRORLOG | grep -a -c ^)" -eq 0 ] && [ "$(lsof /var/cache/apt/archives/lock 2>>$ERRORLOG | grep -a -c ^)" -eq 0 ] && [ "$(lsof /var/cache/apt/archives/lock-frontend 2>>$ERRORLOG | grep -a -c ^)" -eq 0 ] && [ "$(lsof /var/cache/apt/archives/lock-frontened 2>>$ERRORLOG | grep -a -c ^)" -eq 0 ] && [ "$(lsof /var/lib/dpkg/lock 2>>$ERRORLOG | grep -a -c ^)" -eq 0 ] && [ "$(lsof /var/lib/dpkg/lock-frontend 2>>$ERRORLOG | grep -a -c ^)" -eq 0 ] && [ "$(lsof /var/lib/dpkg/lock-frontened 2>>$ERRORLOG | grep -a -c ^)" -eq 0 ] ; then
		APT="Y"
	else
		APT="N"
	fi
fi

if [ "$CLEAN" = "" ] ; then
	CLEAN="Y"
fi

if [ "$KCLEAN" = "" ] ; then
	KCLEAN="Y"
fi

if [ "$SBIN" = "" ] ; then
	SBIN="Y"
fi

if [ "$TDE_DESKTOP_AUTO" = "" ] ; then
	TDE_DESKTOP_AUTO="Y"
fi

if [ "$MENUGEN" = "" ] ; then
	MENUGEN="Y"
fi

#if [ "$SSH_ROOT_NO" = "" ] ; then
#	SSH_ROOT_NO="Y"
#fi

if [ "$FAIL2BAN_NFTABLES_MULTIPORT" = "" ] ; then
	FAIL2BAN_NFTABLES_MULTIPORT="Y"
fi

if [ "$SEC_DNS" = "" ] ; then
	SEC_DNS="Y"
fi


### ROOT CHECK ########################################

#if [ "$(cat /etc/passwd | grep -aE ^$(whoami): | cut -d ':' -f 3 )" -ne 0 ] ; then
if [ "$(id -u)" -ne 0 ] ; then
	echo $"$TITLE must be launched as SuperUser. Cannot continue."
	exit 1
fi
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/trinity/bin


### SCRIPT ########################################

if [ -e /etc/picalibre_version ] ; then PRE_PICAVERSION=$(cat /etc/picalibre_version | cut -d '.' -f 1 ) ; fi
if [ -e /etc/debian_version ] ; then PRE_DEBIANVERSION=$(cat /etc/debian_version | cut -d '.' -f 1 ) ; fi
if [ -e /etc/devuan_version ] ; then PRE_DEVUANVERSION=$(expr $(cat /etc/devuan_version | sed -e 's|jessie|1|g' -e 's|ascii|2|g' -e 's|beowulf|3|g' -e 's|chimaera|4|g' -e 's|daedalus|5|g' -e 's|excalibur|6|g' | cut -d '.' -f 1 | sed 's|/ceres||g') + 7 ) ; fi
DEBIANVERSION=$(printf "$PRE_PICAVERSION\n$PRE_DEBIANVERSION\n$PRE_DEVUANVERSION" | sort -n -r | head -n 1 )

DISTRONAME="PicaLibre"
DISTROLABEL="picalibre"
DISTROVERSION="$(cat /etc/apt/sources.list | grep -a picalibre.org | grep -aEv "^#" | awk '{print $3}' | sort -n -r | head -n 1)"

if [ "$MOD_OS_NAME" != "n" ] && [ "$MOD_OS_NAME" != "N" ] && [ "$MOD_OS_NAME" != "No" ] && [ "$MOD_OS_NAME" != "no" ] ; then
	MOD_OS_NAME="Y"
else
	MOD_OS_NAME="N"
fi


# Clean

if [ "$CLEAN" = "Y" ] && [ "$APT" = "Y" ] ; then

# Delete downloaded packages
apt-get clean 2>>"$ERRORLOG"
rm -f /var/cache/apt/archives/*deb
rm -f /var/cache/apt/archives/partial/*deb

fi

if [ "$KCLEAN" = "Y" ] && [ "$APT" = "Y" ] ; then

# Delete old installed kernels
KL="" ; VM="" ; VMprev="" ; VMprevprev="" ; for l in $(ls /boot/ | grep -aEi "^initrd|^vmlinu|^uInitrd" | sed "s|^initr[a-z.]\+-||g" | sed "s|^vmlinu[a-z.]\+-||g" | sed "s|^uInitr[a-z.]\+-||g" | sort -u | grep -aEiv gnu | grep -aEiv "$(uname -r)" | sort -Vr) ; do VMprevprev=$VMprev ; VMprev=$VM ; VM=$(echo $l | cut -d '.' -f 1,2) ; if [ "$VM" = "$VMprev" ] && [ "$VMprev" = "$VMprevprev" ] ; then if [ "$KL" = "" ] ; then KL="$l" ; else KL="$KL|$l" ; fi ; fi ; done ; if [ "$KL" != "" ] ; then KLP=$(dpkg -l | awk '{print $2}' | sed "s|:.*||g" | grep -aEi "^linux-image|^linux-headers" | grep -aEi "$KL") ; fi ; if [ "$KLP" != "" ] ; then apt-get purge -y $(echo "$KLP") 2>>"$ERRORLOG" ; fi
KL="" ; VM="" ; VMprev="" ; VMprevprev="" ; for l in $(ls /boot/ | grep -aEi "^initrd|^vmlinu|^uInitrd" | sed "s|^initr[a-z.]\+-||g" | sed "s|^vmlinu[a-z.]\+-||g" | sed "s|^uInitr[a-z.]\+-||g" | sort -u | grep -aEi gnu | grep -aEiv "$(uname -r)" | sort -Vr) ; do VMprevprev=$VMprev ; VMprev=$VM ; VM=$(echo $l | cut -d '.' -f 1,2) ; if [ "$VM" = "$VMprev" ] && [ "$VMprev" = "$VMprevprev" ] ; then if [ "$KL" = "" ] ; then KL="$l" ; else KL="$KL|$l" ; fi ; fi ; done ; if [ "$KL" != "" ] ; then KLP=$(dpkg -l | awk '{print $2}' | sed "s|:.*||g" | grep -aEi "^linux-image|^linux-headers" | grep -aEi "$KL") ; fi ; if [ "$KLP" != "" ] ; then apt-get purge -y $(echo "$KLP") 2>>"$ERRORLOG" ; fi

fi


# Fix linux-libre
#if [ -e /etc/apt/sources.list.d/freesh.sources ] ; then
#	if [ "$(cat /etc/apt/sources.list.d/freesh.sources | grep -aEi "URIs: mirror|URIs: .*mirrors.txt$")" != "" ] ; then
#		sed -i "s|URIs: .*|URIs: https://linux-libre.fsfla.org/pub/linux-libre/freesh/|g" /etc/apt/sources.list.d/freesh.sources
#	fi
#fi


# Do not encourage the use of privative firmware
find /etc/initramfs-tools/ /usr/share/initramfs-tools/ -type f | while read i ; do
	sed -i "s|echo .* missing firmware.*|continue|g" "$i"
	sed -i "s|echo .* locating .* firmware.*|continue|g" "$i"
done
if [ -e /etc/initramfs-tools/initramfs.conf ] && [ "$(command -v zstd)" = "" ] ; then
	# 'zstd' is setting by default (since 0.141 in 2022) and an annoying message is shown every time initramfs is created if 'zstd' is not installed.
	if [ "$(cat /etc/initramfs-tools/initramfs.conf | grep -a COMPRESS=gzip)" = "" ] ; then
		sed -i "s|COMPRESS=.*|COMPRESS=gzip|g" /etc/initramfs-tools/initramfs.conf
	fi
fi


if [ "$SBIN" = "Y" ] ; then

# Add sbin PATH

if [ -e /etc/profile ] ;then
	if [ "$(cat /etc/profile | grep -a 'PATH=' | grep -av sbin)" != "" ] ; then
		sed -i '/PATH=/{/sbin/! s|"$|:/usr/sbin:/sbin"|g}' /etc/profile
	fi
fi

fi


# Add TDE PATH

if [ -e /etc/apt/sources.list ] ; then
	if [ "$(cat /etc/apt/sources.list | grep -aEi ^deb | grep -aEi trinity)" != "" ] && [ -e /etc/profile ] ; then
		if [ "$(cat /etc/profile | grep -a trinity)" = "" ] ; then
			sed -i '/trinity/! s|:/usr/bin|:/opt/trinity/bin:/usr/bin|g' /etc/profile
		fi
	fi
fi


# Additional GUI su-to-root

if [ "$(command -v su-to-root)" != "" ] ; then
	if [ -e /usr/bin/su-to-root ] ; then
		if [ "$(cat /usr/bin/su-to-root | grep -aEi 'tdesu|lxsu')" = "" ] ; then
			sed -i 's|^        SU_TO_ROOT_X=kde4su|        SU_TO_ROOT_X=kde4su\n      elif test -x /opt/trinity/bin/tdesu ; then\n        SU_TO_ROOT_X=tdesu\n      elif command -v lxsu >/dev/null 2>\&1 ; then\n        SU_TO_ROOT_X=lxsu|g' /usr/bin/su-to-root
			sed -i 's|kde4su) /usr/lib/kde4/libexec/kdesu -u "$PRIV" "$COMMAND";;|kde4su) /usr/lib/kde4/libexec/kdesu -u "$PRIV" "$COMMAND";;\n      tdesu) /opt/trinity/bin/tdesu -u "$PRIV" "$COMMAND";;\n      lxsu) lxsu "$COMMAND";;|g' /usr/bin/su-to-root
		fi
	fi
	if [ -e /usr/sbin/su-to-root ] ; then
		if [ "$(cat /usr/sbin/su-to-root | grep -aEi 'tdesu|lxsu')" = "" ] ; then
			sed -i 's|^        SU_TO_ROOT_X=kde4su|        SU_TO_ROOT_X=kde4su\n      elif test -x /opt/trinity/bin/tdesu ; then\n        SU_TO_ROOT_X=tdesu\n      elif command -v lxsu >/dev/null 2>\&1 ; then\n        SU_TO_ROOT_X=lxsu|g' /usr/sbin/su-to-root
			sed -i 's|kde4su) /usr/lib/kde4/libexec/kdesu -u "$PRIV" "$COMMAND";;|kde4su) /usr/lib/kde4/libexec/kdesu -u "$PRIV" "$COMMAND";;\n      tdesu) /opt/trinity/bin/tdesu -u "$PRIV" "$COMMAND";;\n      lxsu) lxsu "$COMMAND";;|g' /usr/sbin/su-to-root
		fi
	fi
fi


# Fix "No XFCE" in lxpolkit
if [ -e /etc/xdg/autostart/lxpolkit.desktop ] ; then
	if [ "$(cat /etc/xdg/autostart/lxpolkit.desktop | grep -a Not | grep -a XFCE)" != "" ] ; then
		sed -i '/NotShowIn=/ s|;XFCE||g' /etc/xdg/autostart/lxpolkit.desktop
	fi
fi


# Fix SU .desktop

DESKTOP_PATH_LIST="/usr/share/applications /opt/trinity/share/applications/tde"

if [ ! -e /usr/share/menugen/ ] ; then mkdir -p /usr/share/menugen/ ; fi

if [ "$(command -v su-to-root)" != "" ] ; then
	for DESKTOP_PATH in $DESKTOP_PATH_LIST ; do
		if [ -e "$DESKTOP_PATH" ] ; then
			cd "$DESKTOP_PATH"
			ls | grep -a desktop$ | while read i ; do
				# etherape: https://bugs.debian.org/910117
				TEST=$(cat $i | grep -a Exec= | grep -av 'su-to-root' | grep -aEi "=pkexec |=pkexec-|\-pkexec$|\-pkexec |/sbin/|grub-customizer|etherape")
				if [ "$TEST" != "" ] ; then
	#				echo __$i
					sed -i '/Exec=pkexec$/ d' $i
					sed -i 's|Exec=pkexec |Exec=|g' $i
					sed -i 's|Exec=|Exec=su-to-root -X -c |g' $i
					PRECOM="$(cat $i | grep -a Exec= | sed "s|.*xec=su-to-root -X -c ||g" | tr ' ' '\n' | head -n 1)"
					NPRECOM="$(echo $PRECOM | awk -F '/' '{print $NF}')"
					POSTCOM="$(command -v $(echo "$NPRECOM" | sed 's|^pkexec-||g' | sed 's|-pkexec||g'))"
					if [ "$POSTCOM" != "" ] && [ "$PRECOM" != "$POSTCOM" ] ; then
						sed -i "/Exec=/ s|$PRECOM|$POSTCOM|g" $i
					fi
					find /usr/share/polkit-1/actions/ | grep -a pkexec | grep -aEi 'canonical|ubuntu|launchpad' | while read x ; do rm -rf "$x" ; done
					if [ "$(echo $NPRECOM | grep -aEi pkexec)" != "" ] ; then
						find /usr/share/man/ | grep -a $NPRECOM | while read x ; do rm -f "$x" ; done
						rm -rf "$(command -v $NPRECOM)"
					fi
	#				cat $i | grep -a Exec=
				fi
			done
			cd - 1>/dev/null
		fi
	done
fi
# Alternative: Create a second SU .desktop for pkexec-mediated applications
#
#if [ "$(command -v su-to-root)" != "" ] ; then
#	for DESKTOP_PATH in $DESKTOP_PATH_LIST ; do
#		if [ -e "$DESKTOP_PATH" ] ; then
#			cd "$DESKTOP_PATH"
#			ls | grep -a desktop$ | while read i ; do
#				TEST=$(cat $i | grep -a Exec= | grep -av 'su-to-root' | grep -aEi "=pkexec-|\-pkexec$|\-pkexec |/sbin/|grub-customizer|etherape")
#				if [ "$TEST" != "" ] ; then
##					echo __$i
#					cp -a "${i}.desktop" "${i}-su.desktop"
#					sed -i 's|Exec=|Exec=su-to-root -X -c |g' "${i}-su.desktop"
#					PRECOM="$(cat $i | grep -a Exec= | tr '=' '\n' | tr ' ' '\n' | grep -aEi 'pkexec|grub-customizer|etherape')"
#					NPRECOM="$(echo $PRECOM | awk -F '/' '{print $NF}')"
#					POSTCOM="$(command -v $(echo "$NPRECOM" | sed 's|^pkexec-||g' | sed 's|-pkexec||g'))"
#					if [ "$POSTCOM" != "" ] && [ "$PRECOM" != "$POSTCOM" ] ; then
#						sed -i "/Exec=/ s|$PRECOM|$POSTCOM|g" "${i}-su.desktop"
#					fi
#					if [ "$(cat ${i}.desktop | grep -aE ^Name | grep -a '"')" != "" ] ; then sed -i 's|^\(Name.*\)"$|\1 (SU)"|g' "${i}-su.desktop" ; else sed -i 's|^\(Name.*\)$|\1 (SU)|g' "${i}-su.desktop" ; fi    #'
#					if [ "$(cat ${i}.desktop | grep -aE ^GenericName | grep -a '"')" != "" ] ; then sed -i 's|^\(GenericName.*\)"$|\1 (SU)"|g' "${i}-su.desktop" ; else sed -i 's|^\(GenericName.*\)$|\1 (SU)|g' "${i}-su.desktop" ; fi    #'
#					if [ "$(cat ${i}.desktop | grep -aE ^Comment | grep -a '"')" != "" ] ; then sed -i 's|^\(Comment.*\)"$|\1 (SU)"|g' "${i}-su.desktop" ; else sed -i 's|^\(Comment.*\)$|\1 (SU)|g' "${i}-su.desktop" ; fi    #'
#					printf "$DESKTOP_PATH"/"$i".desktop'\t'"$DESKTOP_PATH"/"${i}-su.desktop"'\n' | tee -a /usr/share/menugen/menugen_create
##					cat $i | grep -a Exec=
#				fi
#			done
#			cd - 1>/dev/null
#		fi
#	done
#fi


# Create SU .desktop for file managers and text editors

if [ "$(command -v su-to-root)" != "" ] ; then
	for DESKTOP_PATH in $DESKTOP_PATH_LIST ; do
		if [ -e "$DESKTOP_PATH" ] ; then
			cd "$DESKTOP_PATH"
			ls | grep -a desktop$ | grep -aEi "^caja-browser.desktop$|^org.kde.dolphin.desktop$|^doublecmd.desktop$|^doublecmd-gtk.desktop$|^doublecmd-qt.desktop$|^konqbrowser.desktop$|^org.kde.konqueror.desktop$|^Home.desktop$|^konquerorsu.desktop$|^org.gnome.Nautilus.desktop$|^nemo.desktop$|^pcmanfm.desktop$|^pcmanfm-gtk3.desktop$|^pcmanfm-qt.desktop$|^peony.desktop$|^spacefm.desktop$|^spacefm-gtk3.desktop$|^thunar.desktop$|^org.xfce.thunar.desktop$|^worker.desktop$|^featherpad.desktop$|^gedit.desktop$|^org.gnome.gedit.desktop$|^juffed.desktop$|^leafpad.desktop$|^kwrite.desktop$|^org.kde.kwrite.desktop$|^mousepad.desktop$|^org.xfce.mousepad.desktop$|^pluma.desktop$" | sed "s|.desktop$||g" | while read i ; do
				if [ ! -e "${i}su.desktop" ] && [ ! -e "${i}-su.desktop" ] ; then
					cp -a "${i}.desktop" "${i}-su.desktop"
					sed -i 's|Exec=|Exec=su-to-root -X -c |g' "${i}-su.desktop"
					if [ "$(cat ${i}.desktop | grep -aE ^Name | grep -a '"')" != "" ] ; then sed -i 's|^\(Name.*\)"$|\1 (SU)"|g' "${i}-su.desktop" ; else sed -i 's|^\(Name.*\)$|\1 (SU)|g' "${i}-su.desktop" ; fi    #'
					if [ "$(cat ${i}.desktop | grep -aE ^GenericName | grep -a '"')" != "" ] ; then sed -i 's|^\(GenericName.*\)"$|\1 (SU)"|g' "${i}-su.desktop" ; else sed -i 's|^\(GenericName.*\)$|\1 (SU)|g' "${i}-su.desktop" ; fi    #'
					if [ "$(cat ${i}.desktop | grep -aE ^Comment | grep -a '"')" != "" ] ; then sed -i 's|^\(Comment.*\)"$|\1 (SU)"|g' "${i}-su.desktop" ; else sed -i 's|^\(Comment.*\)$|\1 (SU)|g' "${i}-su.desktop" ; fi    #'
					printf "$DESKTOP_PATH"/"$i".desktop'\t'"$DESKTOP_PATH"/"${i}-su.desktop"'\n' | tee -a /usr/share/menugen/menugen_create
				fi
			done
			cd - 1>/dev/null
		fi
	done
fi


# TDE .desktop in /usr/share/applications
if [ "$TDE_DESKTOP_AUTO" = "Y" ] ; then
if [ ! -e /usr/share/menugen/ ] ; then mkdir -p /usr/share/menugen/ ; fi
if [ -e "/opt/trinity/share/applications/tde" ] ; then
	for i in $(ls /opt/trinity/share/applications/tde | grep -a desktop$ | sed "s|.desktop$||g") ; do
		if [ ! -e "/usr/share/applications/$i-trinity.desktop" ] && [ "$(grep -aE /opt/trinity/share/applications/tde/$i.desktop /var/lib/dpkg/info/tdebase-tdeio-plugins-trinity.list /var/lib/dpkg/info/tdebase-trinity-bin.list /var/lib/dpkg/info/tdelibs-data-trinity.list 2>/dev/null)" = "" ] ; then
#			if [ "$i" = "quanta" ] ; then
				if [ ! -e /usr/local/bin/$i-trinity ] ; then
cat > /usr/local/bin/$i-trinity <<EOF
if [ "\$(echo \$PATH | grep -a /opt/trinity/ )" = "" ] ; then
	LIBGL_ALWAYS_SOFTWARE=1 TQT_IM_MODULE=simple PATH=\$PATH:/opt/trinity/bin /opt/trinity/bin/$i "\$@"
else
	LIBGL_ALWAYS_SOFTWARE=1 TQT_IM_MODULE=simple /opt/trinity/bin/$i "\$@"
fi
EOF
					chmod +x /usr/local/bin/$i-trinity
				fi
#				rm /usr/share/applications/$i-trinity.desktop
				cat /opt/trinity/share/applications/tde/$i.desktop | sed "s|Exec=.*|Exec=/usr/local/bin/$i-trinity %U|g" | sed "s|Icon=\(.*\)|Icon=/opt/trinity/share/icons/hicolor/32x32/apps/\1.png|g" >> /usr/share/applications/$i-trinity.desktop
				if [ ! -e "$(cat /usr/share/applications/$i-trinity.desktop | grep -a Icon= | sed 's|Icon=||g')" ] && [ -e "$(cat /usr/share/applications/$i-trinity.desktop | grep -a Icon= | sed 's|Icon=||g' | sed 's|/opt/trinity/share/icons/hicolor/|/opt/trinity/share/icons/crystalsvg/|g')" ] ; then sed -i 's|/opt/trinity/share/icons/hicolor/|/opt/trinity/share/icons/crystalsvg/|g' /usr/share/applications/$i-trinity.desktop ; fi
				printf "/opt/trinity/share/applications/tde/$i.desktop"'\t'"/usr/share/applications/$i-trinity.desktop"'\n' | tee -a /usr/share/menugen/menugen_create
				printf "/opt/trinity/share/applications/tde/$i.desktop"'\t'"/usr/local/bin/$i-trinity"'\n' | tee -a /usr/share/menugen/menugen_create
#			else
##				rm /usr/share/applications/$i-trinity.desktop
#				cat /opt/trinity/share/applications/tde/$i.desktop | sed 's|Exec=|Exec=/opt/trinity/bin/$i %U|g' | sed "s|Icon=\(.*\)|Icon=/opt/trinity/share/icons/hicolor/32x32/apps/\1.png|g" >> /usr/share/applications/$i-trinity.desktop
#				if [ ! -e "$(cat /usr/share/applications/$i-trinity.desktop | grep -a Icon= | sed 's|Icon=||g')" ] && [ -e "$(cat /usr/share/applications/$i-trinity.desktop | grep -a Icon= | sed 's|Icon=||g' | sed 's|/opt/trinity/share/icons/hicolor/|/opt/trinity/share/icons/crystalsvg/|g')" ] ; then sed -i 's|/opt/trinity/share/icons/hicolor/|/opt/trinity/share/icons/crystalsvg/|g' /usr/share/applications/$i-trinity.desktop ; fi
#				printf "/opt/trinity/share/applications/tde/$i.desktop"'\t'"/usr/share/applications/$i-trinity.desktop"'\n' | tee -a /usr/share/menugen/menugen_create
#			fi
		fi
	done
fi
fi


# Add 'NoDisplay=' for XFCE plugin that is displayed in the menu but does not work that way
if [ -e /usr/share/applications/xfce4-sensors.desktop ] ; then
	if [ "$(cat /usr/share/applications/xfce4-sensors.desktop | grep -a NoDisplay)" = "" ] ; then
		sed -i "s|StartupNotify=.*|NoDisplay=true|g" /usr/share/applications/xfce4-sensors.desktop
	fi
fi

# Fix 'NoDisplay=' in official .desktop
if [ -e /usr/share/applications/nm-applet.desktop ] ; then
	if [ "$(cat /usr/share/applications/nm-applet.desktop | grep -a NoDisplay)" != "" ] ; then
		sed -i "s|NoDisplay.*|Categories=Network;|g" /usr/share/applications/nm-applet.desktop
	fi
fi

# Fix 'NotShowIn=' in official .desktop
if [ -e /usr/share/applications/lxrandr.desktop ] ; then
	if [ "$(cat /usr/share/applications/lxrandr.desktop | grep -a NotShowIn)" != "" ] ; then
		sed -i "/NotShowIn.*/d" /usr/share/applications/lxrandr.desktop
	fi
fi

# Fix 'OnlyShowIn=' in official .desktop
if [ -e /usr/share/applications/caja-browser.desktop ] ; then
	if [ "$(cat /usr/share/applications/caja-browser.desktop | grep -a OnlyShowIn)" != "" ] ; then
		sed -i "s|OnlyShowIn.*|NotShowIn=KDE;|g" /usr/share/applications/caja-browser.desktop
	fi
fi
if [ -e /usr/share/applications/xfce4-clipman.desktop ] ; then
	if [ "$(cat /usr/share/applications/xfce4-clipman.desktop | grep -a OnlyShowIn)" != "" ] ; then
		sed -i "s|OnlyShowIn.*|NotShowIn=KDE;|g" /usr/share/applications/xfce4-clipman.desktop
	fi
fi
if [ -e /usr/share/applications/xfce4-clipman-settings.desktop ] ; then
	if [ "$(cat /usr/share/applications/xfce4-clipman-settings.desktop | grep -a OnlyShowIn)" != "" ] ; then
		sed -i "s|OnlyShowIn.*|NotShowIn=KDE;|g" /usr/share/applications/xfce4-clipman-settings.desktop
	fi
fi
if [ -e /usr/share/applications/org.xfce.xfce4-clipman.desktop ] ; then
	if [ "$(cat /usr/share/applications/org.xfce.xfce4-clipman.desktop | grep -a OnlyShowIn)" != "" ] ; then
		sed -i "s|OnlyShowIn.*|NotShowIn=KDE;|g" /usr/share/applications/org.xfce.xfce4-clipman.desktop
	fi
fi
if [ -e /usr/share/applications/org.xfce.xfce4-clipman-settings.desktop ] ; then
	if [ "$(cat /usr/share/applications/org.xfce.xfce4-clipman-settings.desktop | grep -a OnlyShowIn)" != "" ] ; then
		sed -i "s|OnlyShowIn.*|NotShowIn=KDE;|g" /usr/share/applications/org.xfce.xfce4-clipman-settings.desktop
	fi
fi

# Fix problematic 'Exec=' in official .desktop
#if [ -e /usr/share/applications/Rcmdr.desktop ] ; then
#	if [ "$(cat /usr/share/applications/Rcmdr.desktop | grep -aE "Exec=.*/local/bin/Rcmdr")" = "" ] ; then
#		if [ ! -e /usr/local/bin/Rcmdr ] ; then cat /usr/share/applications/Rcmdr.desktop | grep -aE ^Exec= | sed "s|^Exec=||g" > /usr/local/bin/Rcmdr ; chmod +x /usr/local/bin/Rcmdr ; fi
#		sed -i -e "s|Terminal=.*|Terminal=false|g" -e "s|Exec=.*|Exec=$(basename $(command -v sakura lxterminal xfce4-terminal | head -n 1)) -e /usr/local/bin/Rcmdr|g" /usr/share/applications/Rcmdr.desktop
#		printf "/usr/share/applications/Rcmdr.desktop"'\t'"/usr/local/bin/Rcmdr"'\n' | tee -a /usr/share/menugen/menugen_create
#	fi
#fi

# Fix missing icons in official .desktop
if [ -e /usr/share/applications/ibus-setup-cangjie.desktop ] ; then # Alternative: NoDisplay=true
	if [ "$(cat /usr/share/applications/ibus-setup-cangjie.desktop | grep -a Icon=ibus-setup-cangjie)" != "" ] && [ ! -e "/usr/share/icons/ibus-setup-cangjie" ] ; then
		sed -i 's|Icon=ibus-setup-cangjie|Icon=/usr/share/icons/hicolor/16x16/intl/cangjie.png|g' /usr/share/applications/ibus-setup-cangjie.desktop
	fi
fi
if [ -e /usr/share/applications/ibus-setup-quick.desktop ] ; then # Alternative: NoDisplay=true
	if [ "$(cat /usr/share/applications/ibus-setup-quick.desktop | grep -a Icon=ibus-setup-quick)" != "" ] && [ ! -e "/usr/share/icons/ibus-setup-quick" ] ; then
		sed -i 's|Icon=ibus-setup-quick|Icon=/usr/share/icons/hicolor/16x16/intl/quick.png|g' /usr/share/applications/ibus-setup-quick.desktop
	fi
fi
if [ -e /usr/share/applications/valentina.desktop ] ; then
	if [ "$(cat /usr/share/applications/valentina.desktop | grep -a 'Categories=' | grep -ai Utility )" != "" ] ; then
		sed -i '/Categories=/ s|;Utility||g' /usr/share/applications/valentina.desktop
		sed -i 's|Categories=Qt|Categories=Graphics;Qt|g' /usr/share/applications/valentina.desktop
	fi
fi
if [ -e /usr/share/applications/valentina-tape.desktop ] ; then
	if [ "$(cat /usr/share/applications/valentina-tape.desktop | grep -a Icon=valentina-tape)" != "" ] && [ ! -e "/usr/share/icons/valentina-tape" ] ; then
		sed -i 's|Icon=valentina-tape|Icon=tape|g' /usr/share/applications/valentina-tape.desktop
	fi
	if [ "$(cat /usr/share/applications/valentina-tape.desktop | grep -a 'Categories=' | grep -ai Utility )" != "" ] ; then
		sed -i '/Categories=/ s|;Utility||g' /usr/share/applications/valentina-tape.desktop
		sed -i 's|Categories=Qt|Categories=Graphics;Qt|g' /usr/share/applications/valentina-tape.desktop
	fi
fi
if [ -e /usr/share/applications/valentina-puzzle.desktop ] ; then
	if [ "$(cat /usr/share/applications/valentina-puzzle.desktop | grep -a Icon=valentina-puzzle)" != "" ] && [ ! -e "/usr/share/icons/valentina-puzzle" ] ; then
		sed -i 's|Icon=valentina-puzzle|Icon=puzzle|g' /usr/share/applications/valentina-puzzle.desktop
	fi
	if [ "$(cat /usr/share/applications/valentina-puzzle.desktop | grep -a 'Categories=' | grep -ai Utility )" != "" ] ; then
		sed -i '/Categories=/ s|;Utility||g' /usr/share/applications/valentina-puzzle.desktop
		sed -i 's|Categories=Qt|Categories=Graphics;Qt|g' /usr/share/applications/valentina-puzzle.desktop
	fi
fi
if [ -e /usr/share/applications/ua.com.smart-pattern.valentina.desktop ] ; then
	if [ "$(cat /usr/share/applications/ua.com.smart-pattern.valentina.desktop | grep -a 'Categories=' | grep -ai Utility )" != "" ] ; then
		sed -i '/Categories=/ s|;Utility||g' /usr/share/applications/ua.com.smart-pattern.valentina.desktop
	fi
fi
if [ -e /usr/share/applications/ua.com.smart-pattern.valentina-tape.desktop ] ; then
	if [ "$(cat /usr/share/applications/ua.com.smart-pattern.valentina-tape.desktop | grep -a Icon=valentina-tape)" != "" ] && [ ! -e "/usr/share/icons/valentina-tape" ] ; then
		sed -i 's|Icon=valentina-tape|Icon=tape|g' /usr/share/applications/ua.com.smart-pattern.valentina-tape.desktop
	fi
	if [ "$(cat /usr/share/applications/ua.com.smart-pattern.valentina-tape.desktop | grep -a 'Categories=' | grep -ai Utility )" != "" ] ; then
		sed -i '/Categories=/ s|;Utility||g' /usr/share/applications/ua.com.smart-pattern.valentina-tape.desktop
		sed -i 's|Categories=Qt|Categories=Graphics;Qt|g' /usr/share/applications/ua.com.smart-pattern.valentina-tape.desktop
	fi
fi
if [ -e /usr/share/applications/ua.com.smart-pattern.valentina-puzzle.desktop ] ; then
	if [ "$(cat /usr/share/applications/ua.com.smart-pattern.valentina-puzzle.desktop | grep -a Icon=valentina-puzzle)" != "" ] && [ ! -e "/usr/share/icons/valentina-puzzle" ] ; then
		sed -i 's|Icon=valentina-puzzle|Icon=puzzle|g' /usr/share/applications/ua.com.smart-pattern.valentina-puzzle.desktop
	fi
	if [ "$(cat /usr/share/applications/ua.com.smart-pattern.valentina-puzzle.desktop | grep -a 'Categories=' | grep -ai Utility )" != "" ] ; then
		sed -i '/Categories=/ s|;Utility||g' /usr/share/applications/ua.com.smart-pattern.valentina-puzzle.desktop
		sed -i 's|Categories=Qt|Categories=Graphics;Qt|g' /usr/share/applications/ua.com.smart-pattern.valentina-puzzle.desktop
	fi
fi
if [ -e /usr/share/applications/xgps.desktop ] ; then
	if [ "$(cat /usr/share/applications/xgps.desktop | grep -a 'Categories=' | grep -ai Utility )" != "" ] ; then
		sed -i "s|Categories=.*|Categories=Education;Science;Geography;|g" /usr/share/applications/xgps.desktop
	fi
fi
if [ -e /usr/share/applications/xgpsspeed.desktop ] ; then
	if [ "$(cat /usr/share/applications/xgpsspeed.desktop | grep -a 'Categories=' | grep -ai Utility )" != "" ] ; then
		sed -i "s|Categories=.*|Categories=Education;Science;Geography;|g" /usr/share/applications/xgpsspeed.desktop
	fi
fi
if [ -e /usr/share/applications/COLMAP.desktop ] ; then
	if [ "$(cat /usr/share/applications/COLMAP.desktop | grep -a Icon=colmap)" != "" ] && [ ! -e "/usr/share/icons/colmap" ] ; then
		sed -i 's|Icon=colmap|Icon=/opt/trinity/share/icons/crystalsvg/32x32/devices/camera-photo.png|g' /usr/share/applications/COLMAP.desktop
	fi
fi
if [ -e /usr/share/applications/qwo.desktop ] ; then
	if [ "$(cat /usr/share/applications/qwo.desktop | grep -a Icon=qwo)" != "" ] && [ ! -e "/usr/share/icons/qwo" ] ; then
		sed -i 's|Icon=qwo|Icon=/usr/share/qwo/extra.png|g' /usr/share/applications/qwo.desktop
	fi
fi
if [ -e /usr/share/applications/xgps.desktop ] ; then
	if [ "$(cat /usr/share/applications/xgps.desktop | grep -a Icon=/usr/local/share/gpsd/)" != "" ] ; then
		sed -i 's|Icon=/usr/local/share/gpsd/|Icon=/usr/share/gpsd/|g' /usr/share/applications/xgps.desktop
	fi
fi
if [ -e /usr/share/applications/xgpsspeed.desktop ] ; then
	if [ "$(cat /usr/share/applications/xgpsspeed.desktop | grep -a Icon=/usr/local/share/gpsd/)" != "" ] ; then
		sed -i 's|Icon=/usr/local/share/gpsd/|Icon=/usr/share/gpsd/|g' /usr/share/applications/xgpsspeed.desktop
	fi
fi


# 'xdg-open' ('xdg-utils' package) use /usr/share/applications/mimeinfo.cache (created by 'update-desktop-database', 'desktop-file-utils' package) order
if [ -e "/usr/share/applications/mimeinfo.cache" ] ; then
	if [ "$(cat /usr/share/applications/mimeinfo.cache | grep -a 'inode/directory=' | sed 's|inode/directory=||g' | cut -d ';' -f 1 | grep -aEi "^caja-browser.desktop|^org.kde.dolphin.desktop|^doublecmd.desktop|^doublecmd-gtk.desktop|^doublecmd-qt.desktop|^konqbrowser.desktop|^org.kde.konqueror.desktop|^Home.desktop|^konquerorsu.desktop|^org.gnome.Nautilus.desktop|^nemo.desktop|^pcmanfm.desktop|^pcmanfm-gtk3.desktop|^pcmanfm-qt.desktop|^peony.desktop|^spacefm.desktop|^spacefm-gtk3.desktop|^thunar.desktop|^org.xfce.thunar.desktop|^worker.desktop")" = "" ] ; then
		NL=$(cat /usr/share/applications/mimeinfo.cache | grep -a 'inode/directory=' | sed 's|inode/directory=||g' | tr ';' "\n" | grep -aEi "^caja-browser.desktop$|^org.kde.dolphin.desktop$|^doublecmd.desktop$|^doublecmd-gtk.desktop$|^doublecmd-qt.desktop$|^konqbrowser.desktop$|^org.kde.konqueror.desktop$|^Home.desktop$|^konquerorsu.desktop$|^org.gnome.Nautilus.desktop$|^nemo.desktop$|^pcmanfm.desktop$|^pcmanfm-gtk3.desktop$|^pcmanfm-qt.desktop$|^peony.desktop$|^spacefm.desktop$|^spacefm-gtk3.desktop$|^thunar.desktop$|^org.xfce.thunar.desktop$|^worker.desktop$" | tr "\n" ';')
		if [ "$NL" != "" ] ; then
			sed -i "s|inode/directory=.*|inode/directory=$NL|g" /usr/share/applications/mimeinfo.cache
		fi
	fi
fi

# Thunar contextual menu
for i in /root $(find /home/ -mindepth 1 -maxdepth 1 -type d | grep -aiv 'lost+found') ; do
	if [ -e "$i/.config/Thunar/uca.xml" ] ; then
		if   [ -e /opt/trinity/bin/kdiff3   ] && [ "$(cat $i/.config/Thunar/uca.xml | grep -a kdiff3)" = ""  ] ; then
			sed -i 's|</actions>|<action>\n\t<icon>/opt/trinity/share/icons/hicolor/32x32/apps/kdiff3.png</icon>\n\t<name>KDiff3</name>\n\t<command>/opt/trinity/bin/kdiff3 %F</command>\n\t<description>KDiff3</description>\n\t<patterns>*</patterns>\n\t<directories/>\n\t<audio-files/>\n\t<image-files/>\n\t<other-files/>\n\t<text-files/>\n\t<video-files/>\n</action>\n</actions>|g' "$i/.config/Thunar/uca.xml"
			chown "$(echo $i | sed 's|.*/||g'):$(echo $i | sed 's|.*/||g')" "$i/.config/Thunar/uca.xml"
		elif [ ! -e /opt/trinity/bin/kdiff3 ] && [ "$(cat $i/.config/Thunar/uca.xml | grep -a kdiff3)" != "" ] ; then
			if [ "$(cat $i/.config/Thunar/uca.xml | grep -a '<action><')" != "" ] ; then sed -i -e 's|<action>|\n<action>\n|g' -e 's|</action>|\n</action>\n|g' -e 's|<actions>|\n<actions>\n|g' -e 's|</actions>|\n</actions>\n|g' "$i/.config/Thunar/uca.xml" ; sed -i "/^$/d" "$i/.config/Thunar/uca.xml" ; fi
			N=0 ; for l in $(cat $i/.config/Thunar/uca.xml | grep -n -aEi '<action>|</action>|<command>' | grep -a -A1 -B1 kdiff3 | grep -av kdiff3 | sed 's|:.*||g') ; do N=$(expr $N + 1 ) ; declare "V$N=$l" ; done
			sed -i "${V1},${V2}d" "$i/.config/Thunar/uca.xml" ; unset V1 V2
			chown "$(echo $i | sed 's|.*/||g'):$(echo $i | sed 's|.*/||g')" "$i/.config/Thunar/uca.xml"
		else
		#elif [ -e /opt/trinity/bin/kdiff3   ] && [ "$(cat $i/.config/Thunar/uca.xml | grep -a kdiff3)" != "" ] ; then
		#elif [ ! -e /opt/trinity/bin/kdiff3 ] && [ "$(cat $i/.config/Thunar/uca.xml | grep -a kdiff3)" = ""  ] ; then
			true
		fi
	fi
done


# Fix translation path
if [ -e "/usr/share/locale/es_AR/LC_MESSAGES/x-tile.mo" ] && [ ! -e "/usr/share/locale/es/LC_MESSAGES/x-tile.mo" ] ; then
	cp -a "/usr/share/locale/es_AR/LC_MESSAGES/x-tile.mo" "/usr/share/locale/es/LC_MESSAGES/x-tile.mo"
	printf "/usr/share/locale/es_AR/LC_MESSAGES/x-tile.mo"'\t'"/usr/share/locale/es/LC_MESSAGES/x-tile.mo"'\n' | tee -a /usr/share/menugen/menugen_create
fi


# Fix bin not x
ls -l /usr/bin/ | grep -aEi "^\-" | grep -aEiv "^[a-z-]+x" | awk '{print $NF}' | while read  i ; do ls -l /usr/bin/"$i" ; chmod a+x /usr/bin/"$i" ; ls -l /usr/bin/"$i" ; done


# menugen

if [ "$MENUGEN" = "Y" ] && [ "$(command -v update-menus)" != "" ] ; then

menugen

fi


echo $"Please wait..."


# Clean web browsers of unwanted promotion of the use of privative software and services.

# Firefox

# Sadly Mozilla makes the cleaning of private services more and more a painful and almost impossible task.
PREPWD=$(pwd)
for d in /usr/lib/firefox-esr/ /usr/lib/firefox-esr/browser/ ; do
if [ -e "$d/omni.ja" ] ; then
	cd "$d"
	OMNI=""
	for i in unzip unar 7z 7zz ; do
		if [ "$(command -v $i)" != "" ] && [ "$(command -v zip)" != "" ] ; then
			if [ "$i" = "unzip" ] ; then
				OMNI="Y"
				unzip -q omni.ja -d omni
			elif [ "$i" = "unar" ] ; then
				OMNI="Y"
				unar -q omni.ja
			elif [ "$i" = "7z" ] ; then
				OMNI="Y"
				7z x -oomni omni.ja
			elif [ "$i" = "7zz" ] ; then
				OMNI="Y"
				7zz x -oomni omni.ja
			else
				OMNI="N"
				echo "No zip, unzip, unar, 7z, 7zz"
			fi
			break
		fi
	done
	if [ "$OMNI" = "Y" ] ; then
		rm -f omni.ja
		cd omni
		rm -rf chrome/browser/search-extensions/* chrome/browser/res/activity-stream/data/content/tippytop/images/* chrome/browser/res/activity-stream/data/content/tippytop/favicons/* chrome/browser/content/activity-stream/data/content/tippytop/images/* chrome/browser/content/activity-stream/data/content/tippytop/favicons/*
		rm -rf defaults/settings/main/search-config-icons/*
		find defaults/settings/main/ -type f 2>/dev/null | grep -aEi 'search|top-sites' | while read i ; do
cat > $i <<EOF
{
  "data": [],
  "timestamp": 0
}
EOF
		done
		if [ -e "defaults/settings/main/search-config-v2.json" ] ; then
cat > defaults/settings/main/search-config-v2.json <<EOF
{
  "data": [
    {
      "globalDefault": "searx",
      "recordType": "defaultEngines",
      "schema": 1702901837584,
      "specificDefaults": []
    },
    {
      "recordType": "engineOrders",
      "schema": 1707824831520,
      "orders": [
        {
          "environment": {
            "distributions": []
          },
          "order": [
            "searx",
            "startpage"
          ]
        }
      ]
    },
    {
      "base": {
        "aliases": [
          "searx"
        ],
        "classification": "general",
        "name": "SearX",
        "urls": {
          "search": {
            "base": "https://searx.org/",
            "searchTermParamName": "q"
          },
          "suggestions": {
            "base": "https://searx.org/autocompleter",
            "params": [
              {
                "name": "type",
                "value": "json"
              }
            ],
            "searchTermParamName": "q"
          }
        }
      },
      "identifier": "searx",
      "recordType": "engine",
      "schema": 1718698362015,
      "variants": [
        {
          "environment": {
            "allRegionsAndLocales": true
          }
        }
      ]
    },
    {
      "base": {
        "aliases": [
          "startpage"
        ],
        "classification": "general",
        "name": "StartPage",
        "urls": {
          "search": {
            "base": "https://startpage.com/sp/search",
            "searchTermParamName": "q"
          },
          "suggestions": {
            "base": "https://www.startpage.com/osuggestions",
            "params": [
              {
                "name": "type",
                "value": "json"
              }
            ],
            "searchTermParamName": "q"
          }
        }
      },
      "identifier": "startpage",
      "recordType": "engine",
      "schema": 1718698362016,
      "variants": [
        {
          "environment": {
            "allRegionsAndLocales": true
          }
        }
      ]
    }
  ],
  "timestamp": 1729621653527
}
EOF
		fi
		if [ -e "chrome/browser/res/activity-stream/lib/SearchShortcuts.sys.mjs" ] ; then
			printf "" > chrome/browser/res/activity-stream/lib/SearchShortcuts.sys.mjs
		fi
		for i in /usr/lib/firefox-esr/browser/omni/modules/TopSites.sys.mjs /usr/lib/firefox-esr/browser/omni/chrome/browser/res/activity-stream/lib/TopSitesFeed.sys.mjs ; do
			if [ -e "$i" ] ; then
				sed -i '/const SEARCH_FILTERS = /,/];/ {s|const SEARCH_FILTERS = .*|const SEARCH_FILTERS = [];|p;d}' "$i"
			fi
		done
		zip -0DXqr ../omni.ja *
		cd ..
		rm -rf omni
	fi
	cd "$PREPWD"
fi
done

if [ -e /usr/share/firefox-esr/browser/defaults/preferences/firefox.js ] ; then
cat > /usr/share/firefox-esr/browser/defaults/preferences/firefox.js <<EOF
// Start page
pref("browser.aboutwelcome.enabled", false);  // It depends of Firefox version...
pref("browser.newtabpage.enabled", false);
pref("browser.startup.firstrunSkipsHomepage", false);
pref("datareporting.policy.firstRunURL", "");  // Due to custom firefox.js
pref("startup.homepage_override_url", "/usr/share/pica-skel/pica-index.html");
pref("startup.homepage_welcome_url", "/usr/share/pica-skel/pica-index.html");
pref("startup.homepage_welcome_url.additional", "/usr/share/pica-skel/pica-index.html");
pref("browser.startup.homepage", "/usr/share/pica-skel/pica-index.html");
pref("browser.newtabpage.homepage", "/usr/share/pica-skel/pica-index.html");
pref("browser.newtab.url", "/usr/share/pica-skel/pica-index.html");  // Sadly 'browser.newtab.url' was eliminated in Firefox 41 and later without offering an alternative
// Restore previous session at startup
pref("browser.startup.page", 3);
// Search engine: SearX
pref("browser.search.defaultenginename", "SearX");
pref("browser.search.searchEnginesURL", "https://searx.org/");
pref("browser.search.selectedEngine", "SearX");
pref("browser.urlbar.placeholderName", "SearX");
pref("browser.newtabpage.activity-stream.improvesearch.topSiteSearchShortcuts.searchEngines", "SearX");
// URL suggests
// pref("browser.urlbar.maxRichResults", 0);
// pref("browser.search.hiddenOneOffs", "*");
// pref("browser.urlbar.oneOffSearches", false);
// pref("browser.urlbar.searchSuggestionsChoice", false);
// pref("browser.search.suggest.enabled", false);
// pref("browser.urlbar.suggest.engines", false);
// pref("browser.urlbar.suggest.searches", false);
pref("browser.urlbar.suggest.topsites", false);
pref("browser.fixup.alternate.enabled", false);
// No trim URL
pref("browser.urlbar.trimURLs", false);
// (Try) Show Home button
pref("browser.engagement.home-button.has-used", true);
// Ask for folder where to download
pref("browser.download.useDownloadDir", false);
pref("browser.download.autohideButton", false);
// View the Menu
pref("ui.key.menuAccessKey", 112); // F1
// Highlight all search matches
pref("findbar.highlightAll", true);
//  Wrap long text lines
pref("devtools.debugger.ui.editor-wrapping", true);
pref("plain_text.wrap_long_lines", true);
pref("view_source.wrap_long_lines", true);
// No truncate input text
pref("editor.truncate_user_pastes", false);
// Leave the browser window open even after closing all tabs
pref("browser.tabs.closeWindowWithLastTab", false);
// Reduce browser load by making tabs not load until focused (Optional)
pref("browser.tabs.loadInBackground", false);
pref("browser.newtab.preload", false);
pref("dom.image-lazy-loading.enabled", true);
// If free memory < 400 MB, unload unused tabs (tabs have not used or looked at in a while):
// pref("browser.tabs.unloadOnLowMemory", true);
// When divert 'new window' to new tab, keep focus on current tab
pref("browser.tabs.loadDivertedInBackground", true);
pref("browser.tabs.loadBookmarksInBackground", true);
pref("browser.tabs.loadBookmarksInTabs", true);
pref("browser.bookmarks.openInTabClosesMenu", false);
pref("browser.search.context.loadInBackground", true);
// Open in a new tab, no new window, any popup window for external links
pref("browser.link.open_newwindow.override.external", 3);
// No Mozilla adds, suggestions and recommendations
pref("browser.library.activity-stream.enabled", false);
pref("browser.newtabpage.activity-stream.feeds.snippets", false);
pref("browser.newtabpage.activity-stream.asrouter.providers.snippets", "");
pref("browser.newtabpage.activity-stream.feeds.asrouterfeed", false);  // https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections
pref("messaging-system.rsexperimentloader.enabled", false);  // https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections
pref("app.normandy.enabled", false);  // https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections
pref("browser.aboutHomeSnippets.updateUrl", "");  // https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections
pref("browser.search.geoip.url", "");  // https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections
pref("browser.startup.homepage_override.mstone", "ignore");  // https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections
pref("browser.messaging-system.whatsNewPanel.enabled", false);
pref("extensions.getAddons.cache.enabled", false);  // https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections
pref("browser.newtabpage.activity-stream.feeds.recommendationproviderswitcher", false);
pref("extensions.htmlaboutaddons.recommendations.enabled", false);
pref("browser.newtabpage.activity-stream.feeds.system.topsites", false);
pref("browser.newtabpage.activity-stream.feeds.topsites", false);
pref("browser.newtabpage.activity-stream.improvesearch.topSiteSearchShortcuts", false);
pref("browser.newtabpage.activity-stream.topSitesRows", 0);
pref("browser.newtabpage.activity-stream.feeds.section.topstories", false);
pref("browser.newtabpage.activity-stream.feeds.system.topstories", true);
pref("browser.newtabpage.activity-stream.section.topstories.rows", 0);
pref("browser.newtabpage.activity-stream.showSponsored", false);
pref("browser.newtabpage.activity-stream.showSponsoredTopSites", false);
pref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons", false);
pref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features", false);
pref("extensions.getAddons.showPane", false);
pref("security.dialog_enable_delay", 0);
pref("security.notification_enable_delay", 0);
pref("browser.preferences.moreFromMozilla", false);
pref("browser.urlbar.groupLabels.enabled", false);
pref("browser.urlbar.suggest.quicksuggest.sponsored", false);
pref("browser.urlbar.suggest.quicksuggest.nonsponsored", false);
pref("browser.newtabpage.activity-stream.discoverystream.enabled", false);
pref("browser.newtabpage.activity-stream.feeds.discoverystreamfeed", false);
pref("browser.discovery.containers.enabled", false);
pref("browser.discovery.enabled", false);
pref("browser.newtabpage.activity-stream.feeds.places", false);
pref("browser.newtabpage.activity-stream.feeds.section.highlights", false);
pref("browser.newtabpage.activity-stream.feeds.sections", false);
pref("browser.newtabpage.activity-stream.section.highlights.includePocket", false);
pref("browser.newtabpage.activity-stream.section.highlights.rows", 0);
pref("browser.newtabpage.activity-stream.showSearch", false);
pref("browser.discovery.containers.enabled", false);
pref("browser.discovery.enabled", false);
pref("browser.discovery.sites", "");
pref("browser.newtabpage.activity-stream.discoverystream.enabled", false);
pref("corroborator.enabled", false);
pref("app.shield.optoutstudies.enabled", false);
pref("browser.privatebrowsing.vpnpromourl", "");
pref("identity.fxaccounts.enabled", false);
pref("identity.fxaccounts.toolbar.enabled", false);
pref("extensions.pocket.enabled", false);
pref("extensions.pocket.api", "");
pref("extensions.pocket.oAuthConsumerKey", "");
pref("extensions.pocket.site", "");
pref("browser.tabs.crashReporting.sendReport", false);
// Anti-tracking
pref("browser.contentblocking.category", "strict");
pref("browser.contentblocking.customBlockList.preferences.ui.enabled", true);  // https://bugzilla.mozilla.org/1568900
pref("privacy.donottrackheader.enabled", true);
pref("privacy.trackingprotection.enabled", true);  // https://wiki.mozilla.org/Security/Tracking_protection
pref("privacy.trackingprotection.socialtracking.enabled", true);
pref("privacy.purge_trackers.enabled", true);
pref("privacy.socialtracking.block_cookies.enabled", true);
pref("beacon.enabled", false);  // https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon
pref("network.cookie.thirdparty.sessionOnly", true);
pref("network.cookie.thirdparty.nonsecureSessionOnly", true);
pref("network.preload", false);
pref("network.predictor.enabled", false);
pref("network.predictor.enable-prefetch", false);
pref("network.prefetch-next", false);  // Link prefetching  https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections
pref("network.dns.disablePrefetch", true);  // DNS prefetching  https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections
pref("browser.urlbar.speculativeConnect.enabled", false);  // Speculative pre-connections  https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections
pref("network.http.speculative-parallel-limit", 0);  // Speculative pre-connections  https://support.mozilla.org/en-US/kb/how-stop-firefox-making-automatic-connections
pref("browser.region.update.enabled", false);  // Firefox monitors user location to show local search engines and content.
pref("browser.region.network.scan", false);
pref("browser.region.network.url", "");
pref("dom.push.enabled", false);
pref("dom.push.userAgentID", "");
pref("browser.safebrowsing.downloads.remote.enabled", false);  // https://feeding.cloud.geek.nz/posts/how-safe-browsing-works-in-firefox/
pref("browser.safebrowsing.allowOverride", true);
pref("network.auth.subresource-http-auth-allow", 1);  // 1 = don't allow cross-origin HTTP authentication credentials dialogs
pref("permissions.delegation.enabled", false);
// No autoplay
pref("media.autoplay.allow-extension-background-pages", false);
pref("media.autoplay.block-event.enabled", true);
pref("media.autoplay.block-webaudio", true);
pref("media.autoplay.blocking_policy", 2);
pref("media.autoplay.default", 5);
pref("media.block-autoplay-until-in-foreground", true);
// Strengthen HTTPS
pref("dom.security.https_first", true);
pref("security.ssl.treat_unsafe_negotiation_as_broken", true);
pref("security.ssl.require_safe_negotiation", true);
pref("browser.xul.error_pages.expert_bad_cert", true);
pref("security.mixed_content.block_active_content", true);  // Block no-HTTPS active content (scripts) on HTTPS pages
pref("security.mixed_content.block_object_subrequest", true);  // Block no-HTTPS object content (as Java or Flash) on HTTPS pages
pref("network.security.esni.enabled", true);  // https://www.cloudflare.com/es-es/ssl/encrypted-sni
pref("network.dns.echconfig.enabled", true);
pref("network.dns.use_https_rr_as_altsvc", true);
// (Manual) "Clear Recent History" default
pref("privacy.sanitize.timeSpan", 0);  // 0 = everything (At any time)
pref("privacy.cpd.history", false);
pref("privacy.cpd.downloads", false);
pref("privacy.cpd.formdata", true);
pref("privacy.cpd.cookies", true);
pref("privacy.cpd.cache", true);
pref("privacy.cpd.sessions", true);
pref("privacy.cpd.offlineApps", true);
pref("privacy.cpd.siteSettings", false);
// Autoclear when the browser closes  // https://www.ghacks.net/overview-firefox-aboutconfig-security-privacy-preferences/
// pref("network.cookie.lifetimePolicy", 2);  // Delete cookies at the end of the session (when the browser closes)
// pref("privacy.sanitize.sanitizeOnShutdown", true);
// pref("privacy.clearOnShutdown.history", false);
// pref("privacy.clearOnShutdown.downloads", false);
// pref("privacy.clearOnShutdown.formData", true);
// pref("privacy.clearOnShutdown.cookies", true);
// pref("privacy.clearOnShutdown.cache", true);
// pref("privacy.clearOnShutdown.sessions", true);
// pref("privacy.clearOnShutdown.offlineApps", true);
// pref("privacy.clearOnShutdown.siteSettings", false);
// Not save passwords and pay cards
pref("signon.rememberSignons", false);
pref("signon.management.overrideURI", "");
pref("signon.autofillForms", false);
pref("signon.autofillForms.autocompleteOff", true);
pref("signon.showAutoCompleteOrigins", false);
pref("signon.storeWhenAutocompleteOff", false);
pref("signon.formlessCapture.enabled", false);
pref("signon.passwordEditCapture.enabled", false);
pref("browser.contentblocking.report.lockwise.enabled", false);
pref("extensions.formautofill.creditCards.available", false);
pref("extensions.formautofill.creditCards.enabled", false);
// Disk cache (Optional)
pref("browser.cache.disk.enable", false);
pref("browser.cache.offline.enable", false);
pref("browser.cache.offline.storage.enable", false);
// No autoinstall
pref("app.update.auto", false);
pref("browser.search.update", false);
pref("extensions.update.enabled", false);
pref("extensions.autoupdate.enabled", false);
pref("extensions.update.autoUpdateDefault", false);
pref("extensions.postDownloadThirdPartyPrompt", false);  // false = Ask for confirmation before downloading and installing.
// DNS: DNS-over-HTTPS (DoH) but general OS/router DNS-over-TLS (DoT) is better
// pref("network.trr.mode", 3);  // 0 = off (default), 2 = TRR preferred, 3 = TRR only, 5 = TRR disabled
// pref("network.dns.skipTRR-when-parental-control-enabled", false);
// pref("network.trr.enable_when_nrpt_detected", true);
// pref("network.trr.enable_when_proxy_detected", true);
// pref("network.trr.enable_when_vpn_detected", true);
// pref("network.dns.upgrade_with_https_rr", false);
// pref("network.trr.resolvers", "[{ \"name\": \"dns.sb\", \"url\": \"dns.sb/doh\" }]");
// pref("network.trr.uri", "https://185.222.222.222/dns-query");  // https://dns.sb/doh/ Additionally: https://uncensoreddns.org
// pref("network.trr.custom_uri", "https://185.222.222.222/dns-query");  // https://dns.sb/doh/ Additionally: https://uncensoreddns.org
// pref("network.trr.bootstrapAddress", "185.222.222.222");  // https://wiki.mozilla.org/Trusted_Recursive_Resolver#DNS-over-HTTPS_Prefs_in_Firefox
EOF
if [ -e /usr/share/firefox-esr/browser/defaults/preferences/firefox-branding.js ] ; then cat /usr/share/firefox-esr/browser/defaults/preferences/firefox.js > /usr/share/firefox-esr/browser/defaults/preferences/firefox-branding.js ; fi
if [ -e /usr/share/firefox-esr/browser/defaults/preferences/vendor.js ] ; then cat /usr/share/firefox-esr/browser/defaults/preferences/firefox.js > /usr/share/firefox-esr/browser/defaults/preferences/vendor.js ; fi
fi

# Firefox < 57 and forks as Palemoon (Basilisk uses omni.ja)
if [ -e "/usr/lib/palemoon/browser/searchplugins/" ] ; then
if [ "$(ls /usr/lib/palemoon/browser/searchplugins/ | grep -aEi 'amazon.xml|bing.xml|google.xml|yahoo.xml')" != "" ] ; then
rm -rf /usr/lib/palemoon/browser/searchplugins/*
cat > /usr/lib/palemoon/browser/searchplugins/searx.xml <<EOF
<SearchPlugin xmlns="https://www.mozilla.org/2006/browser/search/">
<ShortName>SearX</ShortName>
<LongName>SearX</LongName>
<Description>SearX</Description>
<InputEncoding>UTF-8</InputEncoding>
<Image width="16" height="16">data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAPoAAAD6AG1e1JrAAABrUlEQVQ4y4XTT4iNURjH8c9zzdCUMmShiA2jKLepKSmGlRS6pcHGxoiFpSQbqSlLWSkWk0zJYnTN3WosFLERd8MsZqHEYox/SWHuvcfiHnfeO6l5Nuc9nef9Pb/v85wTUK4k6MVeHEcZPZjBFB7hZwSvp0IxIv/cj8s4h9X4hBbW53USV/Ae6rVFkR70YQzn8QL38LtQ5GhwKrEOo5gvOihhBGfwGCcwi/0YxmFUE3fy9+mIDnLHwVks4Bo+ZvtP0MSejDaBAziZknF8KToYwlu8ynwL9Vr8QTPC09zAnXiOrdi0FKEP35dwq9dCajv9gDX4hpU5v0tgHhvzJDoxeCwVtzPYgh/4ulRgGgM41NWghU5ONTd2GC//jbIocBNzuJqSgyiVK0mr1MkpYyxCP35hVddF2lVJoj3f67nzD/EMDQxiJMJmSEkTd3EJn3saizexhCP5YKhQpZH5eyNszyIt3McFzAVt7kBiba66DSvwLnNvwO0Iu7NIwgNc7H4Z/4lyJcnqO3Arwr58lFIyWVpOoF4L2oN5g9GUTGcXs5hY1kHRScYcwA2MR6j+BeFchXRl8r9jAAAAAElFTkSuQmCC</Image>
<Url type="text/html" method="get" template="https://searx.org/?q={searchTerms}""/>
<Url type="application/x-suggestions+json" template="https://searx.org/?q={searchTerms}""/>
</SearchPlugin>
EOF
fi
fi

# Konqueror Trinity
if [ -e /opt/trinity/share/apps/konqueror/icons/crystalsvg/16x16/actions/google.png ] ; then cp -a --remove-destination /opt/trinity/share/apps/konqueror/icons/crystalsvg/16x16/actions/trinity1.png /opt/trinity/share/apps/konqueror/icons/crystalsvg/16x16/actions/google.png ; fi
if [ -e "/opt/trinity/share/services/searchproviders/" ] ; then
if [ "$(ls /opt/trinity/share/services/searchproviders/ | grep -aEi 'amazon.desktop|bing.desktop|google.desktop|yahoo.desktop')" != "" ] ; then
rm -rf /opt/trinity/share/services/searchproviders/*
cat > /opt/trinity/share/services/searchproviders/searx.desktop <<EOF
[Desktop Entry]
Type=Service
Name=SearX
X-TDE-ServiceTypes=SearchProvider
Keys=gg,google,sx
Query=https://searx.org/?q=\\{@}
Charset=utf8
EOF
fi
fi

# KDE5 kservices5/searchproviders
if [ -e "/usr/share/kservices5/searchproviders/" ] ; then
if [ "$(ls /usr/share/kservices5/searchproviders/ | grep -aEi 'amazon.desktop|bing.desktop|google.desktop|yahoo.desktop')" != "" ] ; then
rm -rf /usr/share/kservices5/searchproviders/*
cat > /usr/share/kservices5/searchproviders/searx.desktop <<EOF
[Desktop Entry]
Type=Service
Icon=kde
Name=SearX
X-KDE-ServiceTypes=SearchProvider
Keys=gg,google,sx
Query=https://searx.org/?q=\\{@}
Charset=utf8
EOF
fi
fi

# Konqueror Plasma
if [ -e "/usr/share/konqueror/icons/hicolor/16x16/actions/google.png" ] ; then
for i in 16x16 22x22 32x32 48x48 64x64 ; do cp -a --remove-destination /usr/share/icons/hicolor/$i/apps/konqueror.png /usr/share/konqueror/icons/hicolor/$i/actions/google.png ; cp -a --remove-destination /usr/share/icons/hicolor/$i/apps/konqueror.png /usr/share/konqueror/icons/hicolor/scalable/actions/google.svgz ; done
fi
if [ -e "/usr/share/konqueror/opensearch/" ] ; then
if [ "$(ls /usr/share/konqueror/opensearch/ | grep -aEi 'amazon.desktop|bing.desktop|google.desktop|yahoo.desktop')" != "" ] ; then
rm -rf /usr/share/konqueror/opensearch/*
cat > /usr/share/konqueror/opensearch/searx.xml <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<OpenSearchDescription xmlns="https://a9.com/-/spec/opensearch/1.1/">
	<ShortName>SearX</ShortName>
	<LongName>SearX</LongName>
	<Description>SearX</Description>
	<InputEncoding>UTF-8</InputEncoding>
	<Url method="get" type="text/html" template="https://searx.org/?q={searchTerms}""/>
	<Url method="get" type="application/x-suggestions+json" template="https://searx.org/?q={searchTerms}""/>
	<Image width="16" height="16">data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAPoAAAD6AG1e1JrAAABrUlEQVQ4y4XTT4iNURjH8c9zzdCUMmShiA2jKLepKSmGlRS6pcHGxoiFpSQbqSlLWSkWk0zJYnTN3WosFLERd8MsZqHEYox/SWHuvcfiHnfeO6l5Nuc9nef9Pb/v85wTUK4k6MVeHEcZPZjBFB7hZwSvp0IxIv/cj8s4h9X4hBbW53USV/Ae6rVFkR70YQzn8QL38LtQ5GhwKrEOo5gvOihhBGfwGCcwi/0YxmFUE3fy9+mIDnLHwVks4Bo+ZvtP0MSejDaBAziZknF8KToYwlu8ynwL9Vr8QTPC09zAnXiOrdi0FKEP35dwq9dCajv9gDX4hpU5v0tgHhvzJDoxeCwVtzPYgh/4ulRgGgM41NWghU5ONTd2GC//jbIocBNzuJqSgyiVK0mr1MkpYyxCP35hVddF2lVJoj3f67nzD/EMDQxiJMJmSEkTd3EJn3saizexhCP5YKhQpZH5eyNszyIt3McFzAVt7kBiba66DSvwLnNvwO0Iu7NIwgNc7H4Z/4lyJcnqO3Arwr58lFIyWVpOoF4L2oN5g9GUTGcXs5hY1kHRScYcwA2MR6j+BeFchXRl8r9jAAAAAElFTkSuQmCC</Image>
</OpenSearchDescription>
EOF
fi
fi

# Thunderbird
PREPWD=$(pwd)
for d in /usr/lib/thunderbird/ /usr/lib/thunderbird/messenger/ ; do
if [ -e "$d/omni.ja" ] ; then
	cd "$d"
	OMNI=""
	for i in unzip unar 7z 7zz ; do
		if [ "$(command -v $i)" != "" ] && [ "$(command -v zip)" != "" ] ; then
			if [ "$i" = "unzip" ] ; then
				OMNI="Y"
				unzip -q omni.ja -d omni
			elif [ "$i" = "unar" ] ; then
				OMNI="Y"
				unar -q omni.ja
			elif [ "$i" = "7z" ] ; then
				OMNI="Y"
				7z x -oomni omni.ja
			elif [ "$i" = "7zz" ] ; then
				OMNI="Y"
				7zz x -oomni omni.ja
			else
				OMNI="N"
				echo "No zip, unzip, unar, 7z, 7zz"
			fi
			break
		fi
	done
	if [ "$OMNI" = "Y" ] ; then
		rm -f omni.ja
		cd omni
		rm -rf chrome/messenger/search-extensions/* chrome/messenger/res/activity-stream/data/content/tippytop/images/* chrome/messenger/res/activity-stream/data/content/tippytop/favicons/* chrome/messenger/content/activity-stream/data/content/tippytop/images/* chrome/messenger/content/activity-stream/data/content/tippytop/favicons/*
		rm -rf defaults/settings/main/search-config-icons/*
		find defaults/settings/main/ -type f 2>/dev/null | grep -aEi 'search|top-sites' | while read i ; do
cat > $i <<EOF
{
  "data": [],
  "timestamp": 0
}
EOF
		done
		if [ -e "defaults/settings/main/search-config-v2.json" ] ; then
cat > defaults/settings/main/search-config-v2.json <<EOF
{
  "data": [
    {
      "globalDefault": "searx",
      "recordType": "defaultEngines",
      "schema": 1702901837584,
      "specificDefaults": []
    },
    {
      "recordType": "engineOrders",
      "schema": 1707824831520,
      "orders": [
        {
          "environment": {
            "distributions": []
          },
          "order": [
            "searx",
            "startpage"
          ]
        }
      ]
    },
    {
      "base": {
        "aliases": [
          "searx"
        ],
        "classification": "general",
        "name": "SearX",
        "urls": {
          "search": {
            "base": "https://searx.org/",
            "searchTermParamName": "q"
          },
          "suggestions": {
            "base": "https://searx.org/autocompleter",
            "params": [
              {
                "name": "type",
                "value": "list"
              }
            ],
            "searchTermParamName": "q"
          }
        }
      },
      "identifier": "searx",
      "recordType": "engine",
      "schema": 1718698362015,
      "variants": [
        {
          "environment": {
            "allRegionsAndLocales": true
          }
        }
      ]
    },
    {
      "base": {
        "aliases": [
          "startpage"
        ],
        "classification": "general",
        "name": "StartPage",
        "urls": {
          "search": {
            "base": "https://www.startpage.com/sp/search",
            "searchTermParamName": "q"
          },
          "suggestions": {
            "base": "https://www.startpage.com/osuggestions",
            "params": [
              {
                "name": "type",
                "value": "list"
              }
            ],
            "searchTermParamName": "q"
          }
        }
      },
      "identifier": "startpage",
      "recordType": "engine",
      "schema": 1718698362016,
      "variants": [
        {
          "environment": {
            "allRegionsAndLocales": true
          }
        }
      ]
    }
  ],
  "timestamp": 1729621653527
}
EOF
		fi
		if [ -e "chrome/messenger/res/activity-stream/lib/SearchShortcuts.sys.mjs" ] ; then
			printf "" > chrome/messenger/res/activity-stream/lib/SearchShortcuts.sys.mjs
		fi
		for i in /usr/lib/thunderbird/messenger/omni/modules/TopSites.sys.mjs /usr/lib/thunderbird/messenger/omni/chrome/messenger/res/activity-stream/lib/TopSitesFeed.sys.mjs ; do
			if [ -e "$i" ] ; then
				sed -i '/const SEARCH_FILTERS = /,/];/ {s|const SEARCH_FILTERS = .*|const SEARCH_FILTERS = [];|p;d}' "$i"
			fi
		done
		zip -0DXqr ../omni.ja *
		cd ..
		rm -rf omni
	fi
	cd "$PREPWD"
fi
done


# Clean the operating system of unwanted extensions that promote the use of privative software and services.

rm -rf $(echo $(find /usr/lib/ /usr/libexec/ /usr/share/ /opt/trinity/lib/ /opt/trinity/share/ -type f 2>/dev/null | grep -aEi '/gthumb/extensions/|/schemas/org.gnome.gthumb.|/gthumb/ui/|/gthumb/icons/hicolor/|/kipiplugin_|/apps/kipi-|/plasma_|/searchproviders/|/search_providers/|/opensearch/|/xfce' | grep -aEi 'amazon|picasa|flick|facebook|23|twitter|google|youtube|apple{!t}|microsoft|bing|dropbox|flash|hq|imageshack|imgur|instagram|{!tr}ipod|jalbum|muvee|rajce|shwup|smug|vkontakte|yandex'))


# Modify /etc/rc.local to enable:  Alt  ImprPant-PetSis/PrtSc-SysRq  REFISUB
# https://www.kernel.org/doc/Documentation/admin-guide/sysrq.rst
# https://www.kernel.org/doc/html/latest/admin-guide/sysrq.html

if [ -e /etc/rc.local ] ; then
	if [ "$(cat /etc/rc.local | grep -aE "echo 1 > /proc/sys/kernel/sysrq")" = "" ] ; then
		sed -i "s|^echo .* /proc/sys/kernel/sysrq.*||g" /etc/rc.local
		sed -i ':a;N;$!ba;s|\n\n\n|\n\n|g' /etc/rc.local
		sed -i ':a;N;$!ba;s|\n\n\n|\n\n|g' /etc/rc.local
		#sed -i "s|^exit 0|echo 1 > /proc/sys/kernel/sysrq\n\nexit 0|g" /etc/rc.local
		#sed -i "s|# bits.|&\n\necho 1 > /proc/sys/kernel/sysrq\n|g" /etc/rc.local
		sed -i "0,/^$/ s|^$|&\necho 1 > /proc/sys/kernel/sysrq\n|1" /etc/rc.local
	fi
fi


# Secure GPG

for i in /root $(find /home/ -mindepth 1 -maxdepth 1 -type d | grep -aiv 'lost+found') ; do
if [ -e "$i/.gnupg/" ] && [ ! -e "$i/.gnupg/gpg-agent.conf" ] ; then
cat >> $i/.gnupg/gpg-agent.conf <<EOF
default-cache-ttl 0
default-cache-ttl-ssh 0
max-cache-ttl 0
max-cache-ttl-ssh 0
EOF
chmod 600 $i/.gnupg/gpg-agent.conf
chown "$(echo $i | sed 's|.*/||g'):$(echo $i | sed 's|.*/||g')" "$i/.gnupg/gpg-agent.conf"
fi
done


# Secure SSH

# It is NOT done by default, it requires SSH_ROOT_NO="Y" in /etc/pica-postinst. The default is prohibit-password (or its deprecated alias, without-password): password and keyboard-interactive authentication are disabled for root. https://manpages.debian.org/sshd_config
if [ "$SSH_ROOT_NO" = "Y" ] ; then
if [ -e "/etc/ssh/sshd_config" ] ; then
	if [ "$(cat /etc/ssh/sshd_config | grep -a 'PermitRootLogin no')" = "" ] ; then
		MD5INIsshd=$(md5sum /etc/ssh/sshd_config | awk '{print $1}')
		if [ "$(cat /etc/ssh/sshd_config | grep -aE ^PermitRootLogin)" = "" ] ; then
			sed -i "s|^#PermitRootLogin .*|PermitRootLogin no|" /etc/ssh/sshd_config
		else
			sed -i "s|^PermitRootLogin .*|PermitRootLogin no|g" /etc/ssh/sshd_config
		fi
		if [ "$MD5INIsshd" != "$(md5sum /etc/ssh/sshd_config | awk '{print $1}')" ] ; then
			sleep 3
			#if [ "$(command -v systemctl)" != "" ] ; then systemctl restart ssh.service
			if [ "$(command -v service)" != "" ] ; then
				service ssh restart
			elif [ -e "/etc/init.d/" ] ; then
				/etc/init.d/ssh restart
			else
				true
			fi
		fi
	fi
fi
fi


# Fix fail2ban  https://bugs.debian.org/770171#94  https://bugs.debian.org/1037437#44
if [ -e "/etc/fail2ban/jail.d/defaults-debian.conf" ] || [ -e "/etc/fail2ban/paths-debian.conf" ] ; then
	if [ "$(cat /etc/fail2ban/jail.d/defaults-debian.conf /etc/fail2ban/paths-debian.conf | grep -ai 'backend = systemd')" != "" ] ; then
		sed -i 's|backend = systemd|backend = auto|g' /etc/fail2ban/jail.d/defaults-debian.conf /etc/fail2ban/paths-debian.conf
		sed -i '/systemd/d' /var/log/fail2ban.log
		#if [ "$(command -v systemctl)" != "" ] ; then systemctl stop fail2ban.service
		if [ "$(command -v service)" != "" ] ; then
			service fail2ban stop
		elif [ -e "/etc/init.d/" ] ; then
			/etc/init.d/fail2ban stop
		else
			true
		fi
		echo -e "\e[1;31m"$"Please reinstall (do not delete and then install) fail2ban""\e[0m"
	fi
else

# Secure fail2ban

if [ "$FAIL2BAN_NFTABLES_MULTIPORT" = "Y" ] ; then
if [ "$(dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2}' | sed "s|:.*||g" | grep -aEi "^nftables$" )" != "" ] ; then
if [ -e /etc/fail2ban/jail.conf ] || [ -e /etc/fail2ban/jail.local ] ; then
	if [ -e /etc/fail2ban/jail.conf ] ; then
		MD5INIjailconf=$(md5sum /etc/fail2ban/jail.conf | awk '{print $1}')
		if [ "$(cat /etc/fail2ban/jail.conf | grep -aE "^banaction.* = nftables")" = "" ] ; then
			sed -i 's|banaction = iptables-multiport|banaction = nftables-multiport|g' /etc/fail2ban/jail.conf
			sed -i 's|banaction_allports = iptables-allports|banaction_allports = nftables-allports|g' /etc/fail2ban/jail.conf
		fi
	fi
	if [ -e /etc/fail2ban/jail.local ] ; then
	MD5INIjaillocal=$(md5sum /etc/fail2ban/jail.local | awk '{print $1}')
		if [ "$(cat /etc/fail2ban/jail.local | grep -aE "^banaction.* = nftables")" = "" ] ; then
			sed -i 's|banaction = iptables-multiport|banaction = nftables-multiport|g' /etc/fail2ban/jail.local
			sed -i 's|banaction_allports = iptables-allports|banaction_allports = nftables-allports|g' /etc/fail2ban/jail.local
		fi
	fi
	if [ -e /etc/fail2ban/jail.d/defaults-debian.conf ] ; then
	MD5INIdefdebian=$(md5sum /etc/fail2ban/jail.d/defaults-debian.conf | awk '{print $1}')
		if [ "$(cat /etc/fail2ban/jail.d/defaults-debian.conf | grep -aE "^banaction.* = nftables")" = "" ] ; then
			sed -i 's|banaction = iptables-multiport|banaction = nftables-multiport|g' /etc/fail2ban/jail.d/defaults-debian.conf
			sed -i 's|banaction_allports = iptables-allports|banaction_allports = nftables-allports|g' /etc/fail2ban/jail.d/defaults-debian.conf
		fi
	fi
	if [ "$MD5INIjailconf" != "$(md5sum /etc/fail2ban/jail.conf | awk '{print $1}')" ] || [ "$MD5INIjaillocal" != "$(md5sum /etc/fail2ban/jail.local 2>/dev/null | awk '{print $1}')" ] || [ "$MD5INIdefdebian" != "$(md5sum /etc/fail2ban/jail.d/defaults-debian.conf 2>/dev/null | awk '{print $1}')" ] ; then
		sleep 3
		#if [ "$(command -v systemctl)" != "" ] ; then systemctl restart fail2ban.service
		if [ "$(command -v service)" != "" ] ; then
			service fail2ban restart
		elif [ -e "/etc/init.d/" ] ; then
			/etc/init.d/fail2ban restart
		else
			true
		fi
	fi
fi
fi
fi

fi # Fix fail2ban  https://bugs.debian.org/770171#94  https://bugs.debian.org/1037437#44


# Secure Apache HTTP Server

if [ -e /etc/apache2/conf-available/security.conf ] || [ -e /etc/apache2/apache2.conf ] ; then
	if [ -e /etc/apache2/conf-available/security.conf ] ; then
		MD5INIapachesec=$(md5sum /etc/apache2/conf-available/security.conf | awk '{print $1}')
		if [ "$(cat /etc/apache2/conf-available/security.conf | grep -aEi "^ServerTokens Prod")" = "" ] || [ "$(cat /etc/apache2/conf-available/security.conf | grep -aEi "^ServerSignature Off")" = "" ] ; then
			sed -i "s|^ServerTokens.*|ServerTokens Prod|g" /etc/apache2/conf-available/security.conf
			sed -i "s|^ServerSignature.*|ServerSignature Off|g" /etc/apache2/conf-available/security.conf
		fi
	fi
	if [ -e /etc/apache2/apache2.conf ] ; then
		MD5INIapacheconf=$(md5sum /etc/apache2/apache2.conf | awk '{print $1}')
		if [ "$(cat /etc/apache2/apache2.conf | grep -aEi "^ServerTokens Prod")" = "" ] || [ "$(cat /etc/apache2/apache2.conf | grep -aEi "^ServerSignature Off")" = "" ] ; then
			sed -i "s|^ServerTokens.*|ServerTokens Prod|g" /etc/apache2/apache2.conf
			sed -i "s|^ServerSignature.*|ServerSignature Off|g" /etc/apache2/apache2.conf
		fi
	fi
	if [ "$MD5INIapachesec" != "$(md5sum /etc/apache2/conf-available/security.conf | awk '{print $1}')" ] || [ "$MD5INIapacheconf" != "$(md5sum /etc/apache2/apache2.conf | awk '{print $1}')" ] ; then
		sleep 3
		#if [ "$(command -v systemctl)" != "" ] ; then systemctl restart apache2.service
		if [ "$(command -v service)" != "" ] ; then
			service apache2 restart
		elif [ -e "/etc/init.d/" ] ; then
			/etc/init.d/apache2 restart
		else
			true
		fi
	fi
fi


# Secure NTP/NTS chrony

CHRONYVERS=$(dpkg -l | awk '{print $1,$2,$3}' | grep -aEi ' chrony | chrony:' | awk '{print $3}' | cut -d '.' -f 1 | sort -n | tail -n 1)
if [ "$CHRONYVERS" != "" ] ; then
if [ "$CHRONYVERS" -ge 4 ] ; then

if [ -e "/usr/share/chrony/chrony.conf" ] ; then
if [ "$(cat /usr/share/chrony/chrony.conf | grep -aE ^pool)" != "" ] ; then
	sed -i "s|^pool |#pool |g" /usr/share/chrony/chrony.conf
	sed -i "s|^sourcedir /run/|#sourcedir /run/|g" /usr/share/chrony/chrony.conf
fi
TESTNTS=$(cat /usr/share/chrony/chrony.conf | grep -aEi "^server .* nts")
if [ "$TESTNTS" = "" ] ; then
cat >> /usr/share/chrony/chrony.conf <<EOF

# NTS:
server nts.netnod.se iburst nts
server nts.ntp.se iburst nts
server nts.time.nl iburst nts
server ptbnts1.ptb.de iburst nts
server ptbnts2.ptb.de iburst nts
server ptbnts3.ptb.de iburst nts
EOF
sleep 3
#if [ "$(command -v systemctl)" != "" ] ; then systemctl restart chrony.service
if [ "$(command -v service)" != "" ] ; then
	service chrony restart
elif [ -e "/etc/init.d/" ] ; then
	/etc/init.d/chrony restart
else
	true
fi
sleep 3
fi
fi

if [ -e "/etc/chrony/chrony.conf" ] ; then
if [ "$(cat /etc/chrony/chrony.conf | grep -aE ^pool)" != "" ] ; then
	sed -i "s|^pool |#pool |g" /etc/chrony/chrony.conf
	sed -i "s|^sourcedir /run/|#sourcedir /run/|g" /etc/chrony/chrony.conf
fi
TESTNTS=$(cat /etc/chrony/chrony.conf | grep -aEi "^server .* nts")
if [ "$TESTNTS" = "" ] ; then
cat >> /etc/chrony/chrony.conf <<EOF

# NTS:
server nts.netnod.se iburst nts
server nts.ntp.se iburst nts
server nts.time.nl iburst nts
server ptbnts1.ptb.de iburst nts
server ptbnts2.ptb.de iburst nts
server ptbnts3.ptb.de iburst nts
EOF
sleep 3
#if [ "$(command -v systemctl)" != "" ] ; then systemctl restart chrony.service
if [ "$(command -v service)" != "" ] ; then
	service chrony restart
elif [ -e "/etc/init.d/" ] ; then
	/etc/init.d/chrony restart
else
	true
fi
fi
fi

fi
fi


# Secure NTP/NTS ntpsec

NTPSECVERS=$(dpkg -l | awk '{print $1,$2,$3}' | grep -aEi ' ntpsec | ntpsec:' | awk '{print $3}' | sed "s|+dfsg.*||g" | sed "s|+de.*||g" | sed "s|\.||g" | sort -n | tail -n 1)
if [ "$NTPSECVERS" != "" ] ; then
if [ "$NTPSECVERS" -ge 114 ] ; then

if [ -e "/etc/ntpsec/ntp.conf" ] ; then
if [ "$(cat /etc/ntpsec/ntp.conf | grep -aE ^pool)" != "" ] ; then
	sed -i "s|^pool |#pool |g" /etc/ntpsec/ntp.conf
	sed -i "s|^sourcedir /run/|#sourcedir /run/|g" /etc/ntpsec/ntp.conf
	sed -i 's|IGNORE_DHCP=.*|IGNORE_DHCP="yes"|g' /etc/default/ntpsec
	sed -i "s|^NTPSERVERS=|#NTPSERVERS=|g" /etc/default/ntpsec-ntpdate
fi
TESTNTS=$(cat /etc/ntpsec/ntp.conf | grep -aEi "^server .* nts")
if [ "$TESTNTS" = "" ] ; then
cat >> /etc/ntpsec/ntp.conf <<EOF

# NTS:
server nts.netnod.se nts
server nts.ntp.se nts
server nts.time.nl nts
server ptbnts1.ptb.de nts
server ptbnts2.ptb.de nts
server ptbnts3.ptb.de nts
EOF
sleep 3
#if [ "$(command -v systemctl)" != "" ] ; then systemctl restart ntpsec.service
if [ "$(command -v service)" != "" ] ; then
	service ntpsec restart
elif [ -e "/etc/init.d/" ] ; then
	/etc/init.d/ntpsec restart
else
	true
fi
fi
fi

fi
fi


# Secure DNS
if [ "$SEC_DNS" = "Y" ] ; then
if [ "$(cat /etc/resolv.conf | grep -aEi 'dns.sb|uncensoreddns')" = "" ] ; then
if [ "$APT" = "Y" ] ; then
	dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2}' | sed "s|:.*||g" | grep -aEi 'android-androresolvd|openresolv|resolvconf|resolvconf-admin' | while read i ; do apt-get purge -y $i 2>>"$ERRORLOG" ; done
fi
# Not work "r--r--r--" permissions,  chmod -w /etc/resolv.conf
# "chattr" only works with ext4 and btrfs, not with squashfs (live systems), not nilfs2.
chattr -i /etc/resolv.conf
cat > /etc/resolv.conf <<EOF
# https://dns.sb/dot/
nameserver 185.222.222.222
nameserver 45.11.45.11
nameserver 2a09::
nameserver 2a11::
# https://blog.uncensoreddns.org/dns-servers/
nameserver 91.239.100.100
nameserver 2001:67c:28a4::
nameserver 89.233.43.71
nameserver 2a01:3a0:53:53::
EOF
chattr +i /etc/resolv.conf
if [ "$(command -v service)" != "" ] ; then
	service networking stop 2>>$ERRORLOG
	service networking start 2>>$ERRORLOG
elif [ -e "/etc/init.d/networking" ] ; then
	/etc/init.d/networking stop 2>>$ERRORLOG
	/etc/init.d/networking start 2>>$ERRORLOG
else
	echo ERROR
fi
if [ "$(cat /etc/resolv.conf | grep -aEi 'dns.sb|uncensoreddns')" = "" ] ; then echo ERROR ; fi
fi
fi


# Restore lost 'capabilites'
if [ "$REVSETCAP" != "N" ] ; then
ls /var/lib/dpkg/info/ | grep -aE "postinst$" | while read i ; do if [ "$(cat /var/lib/dpkg/info/$i | grep -a 'setcap ')" != "" ] ; then /var/lib/dpkg/info/$i configure ; fi ; done
fi
if [ "$REVSETCAP" != "N" ] && [ "$(lsblk -r -n -o KNAME,TYPE,FSTYPE,MOUNTPOINT | grep -aEi "squashfs|loop")" = "" ] && [ "$(lsblk -r -n -o FSTYPE $(df / | tail -n 1 | awk '{print $1}') | grep -aEi "^ext|^btrfs")" != "" ] ; then
	if ( [ ! -f /etc/pica-postinst ] ) || ( [ -f /etc/pica-postinst ] && [ "$(cat /etc/pica-postinst | grep -aEi "^REVSETCAP")" = "" ] ) ; then
		echo 'REVSETCAP="N"' >> /etc/pica-postinst
	fi
fi


# Keep custom DEFAULT_GRUB entry if exists (1)
if [ -e "/etc/default/grub" ] ; then
	if [ "$(cat /etc/default/grub | grep -aEi ^GRUB_DEFAULT= | sed 's|GRUB_DEFAULT=||g' | wc -m)" -gt 3 ] ; then
		REST_GRUB_DEFAULT=$(cat /etc/default/grub | grep -aEi ^GRUB_DEFAULT=)
	fi
fi


# Modify base-files and lsb-release
if [ "$MOD_OS_NAME" != "N" ] ; then
	for i in $(command -v update-grub) $(command -v grub-mkconfig) /etc/issue /etc/issue.net /etc/os-release /usr/lib/os-release /usr/share/base-files/dot.bashrc /usr/share/base-files/info.dir /usr/bin/lsb_release /usr/lib/python2.7/dist-packages/lsb_release.py /usr/lib/python3/dist-packages/lsb_release.py /usr/share/pyshared/lsb_release.py /usr/share/base-files/motd /etc/motd /etc/cloud/cloud.cfg /etc/default/grub /etc/default/u-boot /usr/sbin/u-boot-update  # base-files lsb-release grub-common grub2-common
	do
		if [ -e "$i" ] ; then
			if [ "$(cat $i | grep -aEi 'debian|devuan')" != "" ] ; then
				sed -i -e "s|Debian GNU/Linux|$DISTRONAME|g" -e "s|Debian|$DISTRONAME|g" -e "s|bugs.debian|www.$DISTROLABEL|g" -e "s|debian.org/support|$DISTROLABEL.org|g" -e "s|debian|$DISTROLABEL|g" -e "s|Devuan GNU/Linux|$DISTRONAME|g" -e "s|Devuan|$DISTRONAME|g" -e "s|bugs.devuan|www.$DISTROLABEL|g" -e "s|devuan.org/os/community|www.$DISTROLABEL.org|g" -e "s|devuan|$DISTROLABEL|g" -e "s|$DISTROLABEL.org/|$DISTROLABEL.org|g" "$i" ; sed -i "s|@$DISTROLABEL.org|@debian.org|g" "$i"
			fi
			if [ "$i" != "$(command -v update-grub)" ] && [ "$i" != "$(command -v grub-mkconfig)" ] && [ "$i" != "/etc/default/u-boot" ] && [ "$i" != "/usr/sbin/u-boot-update" ] && [ "$i" != "/usr/share/base-files/dot.bashrc" ] && [ "$i" != "/usr/share/base-files/info.dir" ] ; then
				sed -i "/\(NAME\|VERSION\)/ s|[0-9]|$DISTROVERSION|g" "$i"
				sed -i "/\(NAME\|VERSION\)/ s|[0-9][0-9\.]\+|$DISTROVERSION|g" "$i"
				sed -i "/$DISTRONAME/ s|$DISTRONAME [0-9]|$DISTRONAME $DISTROVERSION|g" "$i"
				sed -i "/$DISTRONAME/ s|$DISTRONAME [0-9][0-9\.]\+|$DISTRONAME $DISTROVERSION|g" "$i"
				sed -i "/$DISTRONAME/ s|$DISTRONAME [a-z/]\+|$DISTRONAME $DISTROVERSION|g" "$i"
			fi
		fi
	done
	if [ -e "/etc/update-motd.d/" ] ; then if [ "$(ls /etc/update-motd.d/)" != "" ] ; then rm -rf /etc/update-motd.d/* ; fi ; fi
	if [ "$(cat /usr/share/base-files/motd | grep -a $DISTRONAME)" = "" ] || [ "$(cat /usr/share/base-files/motd | grep -a $DISTROLABEL)" = "" ] ; then
		echo "$DISTRONAME $DISTROVERSION https://$DISTROLABEL.org" > /usr/share/base-files/motd
	fi
	if [ "$(cat /etc/motd | grep -a $DISTRONAME)" = "" ] || [ "$(cat /etc/motd | grep -a $DISTROLABEL)" = "" ] ; then
		echo "$DISTRONAME $DISTROVERSION https://$DISTROLABEL.org" > /etc/motd
	fi
	if [ "$i" = "/etc/cloud/cloud.cfg" ] ; then
		sed -i "s|primary: https://deb.*|primary: https://deb.picalibre.org/|g" "$i"
		sed -i "s|security: https://deb.*|security: https://pkgmaster.devuan.org/merged/|g" "$i"
		sed -i 's|adm, audio, cdrom, dialout, dip, floppy, plugdev, sudo, video|adm, audio, dialout, dip, disk, fuse, input, netdev, plugdev, powerdev, ssh, users, vlock, video|g' "$i"
		sed -i 's| sudo, | |g' "$i"
		sed -i '/sudo: /d' "$i"
	fi
	if [ -e "/usr/share/distro-info/ubuntu.csv" ] ; then rm -rf /usr/share/distro-info/ubuntu.csv ; fi
fi


# Fix LightDM translations
if [ "$(command -v pica-lightdm-translations-fix)" != "" ] ; then
	pica-lightdm-translations-fix
fi


# Recovery custom configuration after reinstallation: lightdm
if [ -e /etc/lightdm/lightdm-gtk-greeter.conf ] ; then
if [ "$(cat /etc/lightdm/lightdm-gtk-greeter.conf | grep -aEi "^background|^user-background|^default-user-image")" = "" ] ; then
	if [ -e /etc/lightdm/lightdm-gtk-greeter.conf.d/01_picalibre.conf ] ; then
cat /etc/lightdm/lightdm-gtk-greeter.conf.d/01_picalibre.conf | grep -aEv "\[greeter\]" >> /etc/lightdm/lightdm-gtk-greeter.conf
	else
cat >> /etc/lightdm/lightdm-gtk-greeter.conf <<EOF

# PicaLibre:
background = #000000
user-background = false
#hide-user-image = true
default-user-image = /usr/share/icons/picalibre/picalibre-trademark/PicaLibre.svg
#a11y-states = +contrast
keyboard = xvkbd -secure
#keyboard = cellwriter --xid --keyboard-only
indicators = ~host;~spacer;~clock;~spacer;~a11y;~session;~language;~power

EOF
	fi
fi
fi


# Re-enable 'os-prober' use by GRUB
if [ "$(dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2}' | sed "s|:.*||g" | grep -aEi "^os-prober$")" != "" ] && [ -e /etc/default/grub ] ; then
if [ "$(cat /etc/default/grub | grep -aEi ^GRUB_DISABLE_OS_PROBER=false)" = "" ] ; then
cat >> /etc/default/grub <<EOF

GRUB_DISABLE_OS_PROBER=false
EOF
fi
fi


# Re-enable GRUB_ENABLE_CRYPTODISK after reinstallation: grub
if [ -e /etc/default/grub ] ; then
if [ "$(cat /etc/default/grub | grep -aEi ^GRUB_ENABLE_CRYPTODISK=)" = "" ] ; then
cat >> /etc/default/grub <<EOF

GRUB_ENABLE_CRYPTODISK=y
EOF
fi
fi


# Recovery custom configuration after reinstallation: grub
if [ -e /etc/default/grub ] ; then
if [ "$(cat /etc/default/grub | grep -aEi ^GRUB_THEME=)" = "" ] ; then
cat >> /etc/default/grub <<EOF

GRUB_THEME=/usr/share/grub/grub.txt
EOF
fi
fi


# Keep custom DEFAULT_GRUB entry if exists (2)
if [ "$REST_GRUB_DEFAULT" != "" ] ; then
	if [ -e "/etc/default/grub" ] ; then
		if [ "$(cat /etc/default/grub | grep -aEi ^GRUB_DEFAULT=)" = "" ] ; then
			echo >> /etc/default/grub
			echo $REST_GRUB_DEFAULT >> /etc/default/grub
			echo >> /etc/default/grub
		else
			sed -i "s|^GRUB_DEFAULT=.*|$REST_GRUB_DEFAULT|g" /etc/default/grub
		fi
	fi
fi


# Keep synchronization between EFI files
# Rename/move or delete '/etc/grub-efi-boot' to disable the following
if [ -s /etc/grub-efi-boot ] ; then
	BOOTPATH=/boot/efi/EFI/$(ls -p /boot/efi/EFI/ | grep -a / | grep -aEi boot | sort -u | tail -n 1)
	if [ "$(echo $BOOTPATH | grep -aEi boot)" != "" ] ; then
		cat /etc/grub-efi-boot | grep -aEi "[a-z]" | while read i ; do
			if [ "$(echo $i | grep -aEi "\.cfg$")" != "" ] ; then
				cp -a --remove-destination $i $BOOTPATH/$(basename $i)
			else
				cp -a --remove-destination $i $BOOTPATH/$(basename $i | sed 's|grub|boot|g')
			fi
		done
	fi
fi


# https://gitlab.xfce.org/xfce/xfdesktop/-/issues/263
# https://gitlab.xfce.org/xfce/xfdesktop/-/tree/master/backgrounds
if [ -e "/usr/share/backgrounds/xfce/" ] ; then
	ls /usr/share/backgrounds/ | grep -aEi picalibre | while read i ; do ln -sf /usr/share/backgrounds/$i /usr/share/backgrounds/xfce/$i ; done
	for i in xfce-x xfce-shapes xfce-verticals xfce-stripes xfce-teal xfce-blue ; do
		if [ "$(ls /usr/share/backgrounds/xfce/ | grep -aEi "^$i\.")" != "" ] ; then
			if [ "$(ls /usr/share/backgrounds/xfce/ | grep -aEi "^$i\." | grep -aEi "\.orig\.")" != "" ] ; then break ; fi
			ls /usr/share/backgrounds/xfce/ | grep -aEi "\.orig\." | while read o ; do
				mv -f "/usr/share/backgrounds/xfce/$o" "/usr/share/backgrounds/xfce/$(echo $o | sed "s|\.orig\.|.|g")"
			done
			cp -a /usr/share/backgrounds/xfce/"$(ls /usr/share/backgrounds/xfce/ | grep -aEi "^$i\." | grep -aEiv "\.orig\.")" /usr/share/backgrounds/xfce/"$(ls /usr/share/backgrounds/xfce/ | grep -aEi "^$i\." | sed "s|\.|.orig.|1")"
			ln -sf /usr/share/backgrounds/PicaLibre_http_fondo_sol.svg /usr/share/backgrounds/xfce/"$(ls /usr/share/backgrounds/xfce/ | grep -aEi "^$i\." | grep -aEiv "\.orig\.")"
			break
		fi
	done
fi


# Broken-device-safety mode for gpsd < 3.23.1
if [ -f /etc/default/gpsd ] ; then
	if [ "$(printf "$(dpkg -l | awk '{print $1,$2,$3}' | grep -aEi ' gpsd | gpsd:' | awk '{print $3}' | cut -d '-' -f 1 | cut -d '+' -f 1)\n3.23.1\n" | sort -V | tail -n 1)" = "3.23.1" ] ; then
		if [ "$(cat /etc/default/gpsd | grep -aEi GPSD_OPTIONS= | grep -aEi "\-b")" = "" ] ; then
			MD5INIgpsd1=$(md5sum /etc/default/gpsd | awk '{print $1}')
			sed -i 's|GPSD_OPTIONS="|GPSD_OPTIONS="-b|g' /etc/default/gpsd
			if [ "$MD5INIgpsd1" != "$(md5sum /etc/default/gpsd | awk '{print $1}')" ] ; then
				sleep 3
				#if [ "$(command -v systemctl)" != "" ] ; then systemctl restart gpsd.service
				if [ "$(command -v service)" != "" ] ; then
					service gpsd restart
				elif [ -e "/etc/init.d/$i" ] ; then
					/etc/init.d/gpsd restart
				else
					true
				fi
			fi
		fi
	fi
fi


# gpsd-hotplug
if [ -f /etc/default/gpsd ] ; then
	if [ -e /lib/udev/gpsd.hotplug ] ; then
		if [ "$(cat /etc/default/gpsd | grep -aEi 'START_DAEMON="false"')" = "" ] ; then
			MD5INIgpsd2=$(md5sum /etc/default/gpsd | awk '{print $1}')
			sed -i 's|START_DAEMON="true"|START_DAEMON="false"|g' /etc/default/gpsd
			if [ "$MD5INIgpsd2" != "$(md5sum /etc/default/gpsd | awk '{print $1}')" ] ; then
				sleep 3
				#if [ "$(command -v systemctl)" != "" ] ; then systemctl restart gpsd.service
				if [ "$(command -v service)" != "" ] ; then
					service gpsd restart
				elif [ -e "/etc/init.d/$i" ] ; then
					/etc/init.d/gpsd restart
				else
					true
				fi
			fi
		fi
	fi
fi


# im-config not support 'yad' but only 'zenity', not support 'dialog' but only 'whiptail'
if [ "$(dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2}' | sed "s|:.*||g" | grep -aEi "^im-config$")" != "" ] ; then
	if [ "$(grep -a yad /usr/bin/im-config /usr/share/im-config/im-config.common)" = "" ] ; then
		if [ "$(command -v yad)" != "" ] && ( [ "$(command -v zenity)" = "" ] || [ -L "$(command -v zenity)" ] ) ; then
			sed -i 's|zenity|yad|g' /usr/bin/im-config /usr/share/im-config/im-config.common
		fi
		if [ "$(command -v dialog)" != "" ] && [ "$(command -v whiptail)" = "" ] ; then
			sed -i 's|whiptail|dialog|g' /usr/bin/im-config /usr/share/im-config/im-config.common
		fi
	fi
fi


# memlockd
if [ -e "/etc/memlockd.cfg" ] ; then
	if [ "$(cat /etc/memlockd.cfg | grep -aEi '/bin/top')" = "" ] ; then
		dpkg -L procps | grep -aEi "/bin/|/sbin/" | while read i ; do
			if [ "$(cat /etc/memlockd.cfg | grep -aEi "$i$")" = "" ] ; then
				echo '+'$i >> /etc/memlockd.cfg
			fi
		done
	fi
	for i in bash cat gpm grep htop iotop sensors login nethogs powertop su ; do
		if [ "$(command -v $i)" != "" ] ; then
			if [ "$(cat /etc/memlockd.cfg | grep -aEi "$(command -v $i)$")" = "" ] ; then
				echo '+'$(command -v $i) >> /etc/memlockd.cfg
			fi
		fi
	done
fi


# corekeeper
if [ -e "/etc/sysctl.d/corekeeper.conf" ] || [ -e "/etc/cron.daily/corekeeper" ] ; then
	if [ ! -e "/etc/corekeeper" ] ; then
cat > /etc/corekeeper <<EOF
DELCRASHDIR="N"
DELTD="365"
EOF
	fi
	if [ "$(cat /var/lib/dpkg/info/corekeeper.postrm | grep -a DELCRASHDIR)" = "" ] ; then
	sed -i "/\/var\/crash/ s|\(.*\)|. /etc/corekeeper ; if [ \"\$DELCRASHDIR\" != \"N\" ] ; then \1 ; fi|g" /var/lib/dpkg/info/corekeeper.postrm  #  ; rm /etc/corekeeper|g"
	sed -i 's:invoke-rc.d procps reload:invoke-rc.d procps reload || invoke-rc.d procps force-reload:g' /var/lib/dpkg/info/corekeeper.postrm
	fi
	if [ "$(cat /etc/cron.daily/corekeeper | grep -a DELTD)" = "" ] ; then
	sed -i "s|7|\$DELTD|g" /etc/cron.daily/corekeeper ; sed -i "s|^find |. /etc/corekeeper\nfind |g" /etc/cron.daily/corekeeper
	fi
fi


# pulseaudio autospawn
#if [ -d "/etc/pulse/client.conf.d/" ] ; then
if [ -e "/etc/pulse/client.conf.d/*" ] ; then
	if [ "$(grep -aEi -r "^autospawn=no" /etc/pulse/client.conf.d/* 2>>"$ERRORLOG")" != "" ] ; then
		find /etc/pulse/client.conf.d/ -type f | while read i ; do
			if [ "$(cat "$i" | grep -aEi "^autospawn=no")" != "" ] ; then
				sed -i "s|^autospawn=no|#autospawn=no|g" "$i"
			fi
		done
	fi
fi


# Set speech-dispatcher to alsa if pulseaudio is not installed
if [ "$(dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2}' | sed "s|:.*||g" | grep -aEi "^pulseaudio$")" = "" ] && [ -e "/etc/speech-dispatcher/speechd.conf" ] ; then
	if [ "$(cat /etc/speech-dispatcher/speechd.conf | grep -aEi AudioOutputMethod | grep -aEi alsa)" = "" ] ; then
		sed -i 's|.*AudioOutputMethod.*|AudioOutputMethod "alsa"|g' /etc/speech-dispatcher/speechd.conf
	fi
fi


# https://bugs.debian.org/977877
if [ -e "/usr/share/initramfs-tools/hooks/keymap" ] || [ -e "$(command -v setupcon)" ] ; then
	if [ "$(cat /usr/share/initramfs-tools/hooks/keymap | grep -a /etc/console-setup/tmpkbd)" != "" ] || [ "$(cat $(command -v setupcon) | grep -a /etc/console-setup/tmpkbd)" != "" ] ; then
		true
	else
		sed -i '/^setupcon / a\if [ "$(ls $DESTDIR/etc/console-setup/ | grep -aEi tmpkbd.[a-zA-Z0-9])" != "" ] ; then mv -f $DESTDIR/etc/console-setup/tmpkbd.* $DESTDIR/etc/console-setup/tmpkbd && sed -i "s|/etc/console-setup/tmpkbd.[a-zA-Z0-9]\\+|/etc/console-setup/tmpkbd|g" $DESTDIR/bin/setupcon || exit 1 ; fi' /usr/share/initramfs-tools/hooks/keymap
		if [ "$?" -ne 0 ] ; then
		echo 'if [ "$(ls $setupdir/etc/console-setup/ | grep -aEi tmpkbd.[a-zA-Z0-9])" != "" ] ; then mv -f $setupdir/etc/console-setup/tmpkbd.* $setupdir/etc/console-setup/tmpkbd && sed -i "s|/etc/console-setup/tmpkbd.[a-zA-Z0-9]\+|/etc/console-setup/tmpkbd|g" $setupdir/bin/setupcon || exit 1 ; fi' >> $(command -v setupcon)
		fi
	fi
fi


# laptop-mode-tools: exaggerated alarming messages at boot
if [ -e "/usr/share/laptop-mode-tools/modules/hdparm" ] ; then
	if [ "$(cat /usr/share/laptop-mode-tools/modules/hdparm | grep -aEi 'ERROR: ')" != "" ] ; then
		sed -i 's| "ERROR: | "Info: |g' /usr/share/laptop-mode-tools/modules/hdparm
	fi
fi


# disappeared groups and users due to systemd-sysusers
if [ -e "/etc/init.d/cups" ] ; then 
	if [ ! -e "/usr/lib/sysusers.d/cups.conf" ] && [ ! -e "/usr/lib/sysusers.d/cupsd.conf" ] && [ ! -e "/usr/lib/sysusers.d/cups-daemon.conf" ]  ; then
		if [ -z "$(getent group lpadmin)" ] ; then 
			addgroup --system lpadmin
		fi
	fi
fi


# pmount leaves the folders without erasing and containing only a file with 'root' as owner
ls /media/ | while read i ; do
	if [ "$(ls -A /media/$i)" = ".created_by_pmount" ] ; then
		rm /media/$i/.created_by_pmount
		rmdir /media/$i
	fi
done


# Here only minimal translation corrections (corrections of one or two strings of a single language of a specific version of the software). Major modifications to translations must be made not here but through the appropriate specific packages.

# Fix a translation in qterminal-l10n (2.1.0-1)
if [ -e "/usr/share/qterminal/translations/qterminal_es.qm" ] ; then
	if [ "$(md5sum /usr/share/qterminal/translations/qterminal_es.qm | awk '{print $1}')" = "0deb56d413fee71cd1db6667cf48db4a" ] ; then
		if [ "$(command -v lconvert)" != "" ] ; then  # qtchooser
			lconvert /usr/share/qterminal/translations/qterminal_es.qm -o /usr/share/qterminal/translations/qterminal_es.po
			sed -i "s|Dividir y ver de arriba a abajo|Vista dividida arriba-abajo|g" /usr/share/qterminal/translations/qterminal_es.po
			cat /usr/share/qterminal/translations/qterminal_es.po | grep -a -A2 -B2 Split | sed -e "s|&View|Vie\&w|g" -e "s|Top-Bottom|Left-Right|g" -e "s|arriba-abajo|izquierda-derecha|g" >> /usr/share/qterminal/translations/qterminal_es.po
			rm /usr/share/qterminal/translations/qterminal_es.qm
			lconvert /usr/share/qterminal/translations/qterminal_es.po -o /usr/share/qterminal/translations/qterminal_es.qm
			rm /usr/share/qterminal/translations/qterminal_es.po
		fi
	fi
fi


# Extras
if [ -d "/etc/pica-postinst.d/" ] ; then
	find /etc/pica-postinst.d/ -type f | sort | grep -aE "\.sh$" | while read i ; do bash "$i" ; done
fi


exit 0
