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

# pica1
#
# Initial customization of systems not installed using Pica-II.
#
# 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, dialog | yad | yad-pica | zenity, debconf, dpkg, findutils, gawk | mawk | original-awk, grep, libc-bin, lsof, passwd, pica-apt, procps, sed
# Recommends: console-setup, locales | locales-all, lxterminal | sakura | xfce4-terminal, menu, pica-skel, tzdata, x11-xkb-utils, xkb-data


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

CNAME="pica1"
VERSION="1.3.1"
TITLE="Pica1"
ICON="/usr/share/icons/pica1.png"

# Location of dependent lib files
LIBDEP=/usr/share/$CNAME

# Translations
if [ "$LANG" = "" ] ; then export $(cat /etc/default/locale | grep -a 'LANG=') ; fi
TEXTDOMAIN=pica1
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=$"Initial customization of systems not installed using Pica-II."
LDESCRIP=$"$TITLE is a tool to initial customization of systems not installed using Pica-II."

# 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=" -t""\t"$"Use terminal interface.""\n"" -k""\t"$"Use 'kdialog' if possible.""\n"" -y""\t"$"Use 'yad' if possible (by default in graphical sessions).""\n"" -z""\t"$"Use 'zenity' if possible.""\n"" -x""\t"$"Show help documentation."

while getopts tkyzx OPTION ; do
	case $OPTION in
		t )   T="Y" ; G="N"      ;;
		k )   SDIALOG="kdialog"  ;;
		y )   SDIALOG="yad"      ;;
		z )   SDIALOG="zenity"   ;;
		x )   docu_info ; exit 0 ;;
	esac
done


### DIALOG ########################################

#DEFAULTDIALOGLIST="yad zenity kdialog"
DEFAULTDIALOGLIST="yad zenity"

#if [ -t 0 ] ; then
if [ "$(setxkbmap 1>/dev/null 2>&1 ; echo $? )" -ne 0 ] ; then
	G="N" ; T="Y"
fi

if [ "$G" != "N" ] ; then
	
	if   [ "$SDIALOG" = "kdialog" ] ; then
		DIALOGLIST="kdialog yad zenity"
	elif [ "$SDIALOG" = "yad" ] ; then
		DIALOGLIST="yad zenity kdialog"
	elif [ "$SDIALOG" = "zenity" ] ; then
		DIALOGLIST="zenity yad kdialog"
	else
		DIALOGLIST="$DEFAULTDIALOGLIST"
	fi
	
	if [ "$DIALOGLIST" = "" ] ; then
		if [ "$DEFAULTDIALOGLIST" != "" ] ; then
			DIALOGLIST="$DEFAULTDIALOGLIST"
		else
			DIALOGLIST="yad zenity kdialog"
		fi
	fi
	
	if [ "$(command -v $DIALOGLIST)" = "" ] ; then
		G="N" ; T="Y"
	fi

fi


if [ "$G" = "N" ] ; then

	if [ "$(command -v dialog)" = "" ] ; then
		echo $"ERROR: No supported dialog is installed. $TITLE cannot continue."
		exit 1
	else
		
		DIALOG="dialog --cr-wrap --keep-window --output-fd 1"
		#DIALOG="dialog --cr-wrap --keep-window --output-fd 1 --no-lines --no-shadow"
		if [ "$TITLE" != "" ] ; then
			WICON="--backtitle $(echo $TITLE | sed 's| |-|g')"
		fi
		WTITLE="--title"
		WTEXT=""
		H="0"
		W="0"
		LH="0"
		CALENDAR="--calendar"
		DATEFORMAT="--date-format %Y-%m-%d"
		WTIME="--timebox"
		TIMEFORMAT="--time-format %H:%M:%S"
		DSEL="--dselect"
		FSEL="--fselect"
		WRITE="--inputbox"
		PREWRITE=""
		COLUMN=""
		PRINTCOLUMN1=""
		PRINTCOLUMN2=""
		HIDECOLUMN1=""
		HIDECOLUMN2=""
		#INPUTSEPARATOR="--column-separator"
		#OUTPUTSEPARATOR="--separate-output"
		MONOLIST="--menu"
		#MONOLIST="--radiolist"
		MULTIPLELIST="--separate-output --checklist"
		PRE=""
		POST="off"
		PRES=""
		POSTS="on"

		INFO="--msgbox"
		WAIT="--infobox"

		QYN="--yesno"
		QYNC="--yesno"
		WYN="--yesno"
		WCC="--yesno"
		WYNC="--yesno"
		WM="--msgbox"
		ERROR="--msgbox"

		FORM="--form"
		FORMT=""
		FORMSELPRE=""
		FORMSELPOST=""
		#FORMCALPRE=""
		#FORMCALPOST=""
		#FORMCLPRE=""
		#FORMCLPOST=""
		PRELAB1="1 1"
		POSTLAB1="1 10 999 0"
		PRELAB2="2 1"
		POSTLAB2="2 10 999 0"
		PRELAB3="3 1"
		POSTLAB3="3 10 999 0"

		YES="--yes-label"
		NO="--no-label"
		OK="--ok-label"
		CONTINUE="--ok-label"
		CANCEL="--cancel-label"
		EXTRABUTTON="--extra-button --extra-label"
	
	fi

else

	for i in $DIALOGLIST ; do

		if [ "$(command -v $i)" != "" ] ; then
	
			if [ "$i" = "yad" ] ; then
		
				if [ "$(yad --version | tail -n 1 | cut -d ' ' -f 1 | cut -d '.' -f 1)" -lt 2 ] ; then
					DIALOG="yad --center"  # --selectable-labels (bug in Yad < 2.0) https://github.com/v1cont/yad/blob/master/NEWS
				else
					DIALOG="yad --center --selectable-labels"  # --on-top
				fi
				if [ "$ICON" != "" ] ; then
					WICON="--window-icon $ICON"
				fi
				WTITLE="--title"
				WTEXT="--text"
				H=""
				if [ "$(yad --version | tail -n 1 | grep -aE ^'7.2')" != "" ] ; then
					W="--width=640"
				else
					W="--width=640 --text-width=640 --fixed"  # https://github.com/v1cont/yad/issues/107  https://github.com/v1cont/yad/issues/140
				fi
				LH=""
				CALENDAR="--calendar"
				DATEFORMAT="--date-format %Y-%m-%d"
				WTIME="--separator=\n --columns 3 --form"
				#TIMEFORMAT="--time-format %H:%M:%S"
				DSEL="--file --directory --filename"  # Deleted *-selection alias for --file in Yad 4.0
				FSEL="--file --filename"              # Deleted *-selection alias for --file in Yad 4.0
				WRITE="--entry"
				PREWRITE="--entry-text"
				COLUMN="--column="
				PRINTCOLUMN1="--print-column=01"
				PRINTCOLUMN2="--print-column=02"
				HIDECOLUMN1="--hide-column=01"
				HIDECOLUMN2="--hide-column=02"
				#INPUTSEPARATOR="--item-separator"
				#OUTPUTSEPARATOR="--separator="
				#MONOLIST="--entry"
				MONOLIST="--separator=\n --list --search-column=1 --no-headers"
				MONOLISTH="--separator=\n --list --search-column=1"
				MULTIPLELIST="--separator= --list --checklist --search-column=2 --no-headers"
				MULTIPLELISTH="--separator= --list --checklist --search-column=2"
				PRE="FALSE"
				POST=""
				PRES="TRUE"
				POSTS=""
				# standard gtk keybindings for next and previous search are ctrl+g and ctrl+shift+g while you can redefine them in gtk-keys.css for your theme  # https://github.com/v1cont/yad/issues/127
			
				INFO="--image=/usr/share/icons/picalibre/rm/play.png --button="$"OK"
				WAIT="--image=/usr/share/icons/picalibre/rm/play.png --no-buttons"
			
				QYN="--image=/usr/share/icons/picalibre/rm/question.png --button="$"Yes"":0 --button="$"No"":1"
				QYNC="--image=/usr/share/icons/picalibre/rm/question.png --button="$"Yes"":0 --button="$"No"":1 --button="$"Cancel"":1"
				WYN="--image=/usr/share/icons/picalibre/rm/warning.png --button="$"Yes"":0 --button="$"No"":1"
				WCC="--image=/usr/share/icons/picalibre/rm/warning.png --button="$"Continue"":0 --button="$"Cancel"":1"
				WYNC="--image=/usr/share/icons/picalibre/rm/warning.png --button="$"Yes"":0 --button="$"No"":1 --button="$"Cancel"":1"
				WM="--image=/usr/share/icons/picalibre/rm/warning.png --button="$"OK"
				ERROR="--image=/usr/share/icons/picalibre/rm/error.png --button="$"OK"
			
				FORM="--separator=\n --form"
				FORMT="--field"
				FORMSELPRE="--field"
				FORMSELPOST=":FL"
				FORMCALPRE="--field"
				FORMCALPOST=":DT"
				FORMCLPRE="--field"
				FORMCLPOST=":CB"
				PRELAB1=""
				POSTLAB1=""
				PRELAB2=""
				POSTLAB2=""
				PRELAB3=""
				POSTLAB3=""
			
				YES="--button"
				NO="--button"
				OK="--button"
				CONTINUE="--button"
				CANCEL="--button"
				EXTRABUTTON="--button"
		
			elif [ "$i" = "zenity" ] ; then
		
				DIALOG="zenity"
				if [ "$ICON" != "" ] ; then
					WICON="--window-icon $ICON"
				fi
				WTITLE="--title"
				WTEXT="--text"
				H=""
				W="--width=640"
				LH=""
				CALENDAR="--calendar"
				DATEFORMAT="--date-format %Y-%m-%d"
				WTIME="--separator : --forms"
				#TIMEFORMAT="--time-format %H:%M:%S"
				DSEL="--file-selection --directory --filename"
				FSEL="--file-selection --filename"
				WRITE="--entry"
				PREWRITE="--entry-text"
				COLUMN="--column="
				PRINTCOLUMN1="--print-column=01"
				PRINTCOLUMN2="--print-column=02"
				HIDECOLUMN1="--hide-column=01"
				HIDECOLUMN2="--hide-column=02"
				#INPUTSEPARATOR=""
				#OUTPUTSEPARATOR="--separator=\n"
				MONOLIST="--separator=\n --list --hide-header"
				MONOLISTH="--separator=\n --list"
				MULTIPLELIST="--separator=\n --list --checklist --hide-header"
				MULTIPLELISTH="--separator=\n --list --checklist"
				PRE="FALSE"
				POST=""
				PRES="TRUE"
				POSTS=""
			
				INFO="--info"
				WAIT="--info"
			
				QYN="--question"
				QYNC="--question"
				WYN="--question"
				WCC="--question"
				WYNC="--question"
				WM="--warning"
				ERROR="--error"
			
				FORM="--forms"
				FORMT="--add-entry"
				FORMSELPRE="--add-entry"
				FORMSELPOST=""
				FORMCALPRE="--add-calendar"
				FORMCALPOST=""
				if [ "$(zenity --version | cut -d '.' -f 1 )" -ge 3 ] || [ "$(zenity --version | sed 's|\.||g')" -ge 3102 ] ; then
					FORMCLPOST="--combo-values"
					FORMCLPRE="--add-combo"
				fi
				PRELAB1=""
				POSTLAB1=""
				PRELAB2=""
				POSTLAB2=""
				PRELAB3=""
				POSTLAB3=""
			
				# Zenity <3 does not support custom buttons.
				if [ "$(zenity --version | cut -d '.' -f 1 )" -ge 3 ] ; then
					YES="--ok-label"
					NO="--cancel-label"
					OK="--ok-label"
					CONTINUE="--ok-label"
					CANCEL="--cancel-label"
					#EXTRABUTTON=""
				fi
		
#			elif [ "$i" = "kdialog" ] ; then
#		
#				# CAUTION: All 'kdialog' (TDE, KDE Plasma 4, KDE Plasma 5, KDE Plasma 6,...) are included here!
#			
#				DIALOG="kdialog"
#				if [ "$ICON" != "" ] ; then
#					WICON="--icon $ICON"
#				fi
#				WTITLE="--title"
#				WTEXT=""
#				H=""
#				W=""
#				LH=""
#				# No "--calendar" in TDE-kdialog + No "--date-format" both TDE and Plasma = There is no usable version of kdialog for calendars
#				#CALENDAR="--calendar"
#				#DATEFORMAT="--date-format %Y-%m-%d"
#				#WTIME="--timebox"
#				#TIMEFORMAT="--time-format %H:%M:%S"
#				DSEL="--getexistingdirectory"
#				FSEL="--getsavefilename"
#				#FSEL="--getopenfilename"
#				WRITE="--inputbox"
#				PREWRITE=""
#				COLUMN=""
#				PRINTCOLUMN1=""
#				PRINTCOLUMN2=""
#				HIDECOLUMN1=""
#				HIDECOLUMN2=""
#				#INPUTSEPARATOR=""
#				#OUTPUTSEPARATOR="--separate-output"
#				MONOLIST="--menu"
#				#MONOLIST="--combobox"
#				#MONOLIST="--radiolist"
#				MULTIPLELIST="--separate-output --checklist"
#				PRE=""
#				POST="off"
#				PRES=""
#				POSTS="on"
#			
#				INFO="--msgbox"
#				WAIT="--msgbox"
#			
#				QYN="--yesno"
#				QYNC="--yesnocancel"
#				WYN="--warningyesno"
#				WCC="--warningcontinuecancel"
#				WYNC="--warningyesnocancel"
#				WM="--sorry"
#				ERROR="--error"
#			
#				# No "--form" in any kdialog version
#				#FORM="--form"
#				#FORMT=""
#				#FORMSELPRE=""
#				#FORMSELPOST=""
#				#FORMCALPRE=""
#				#FORMCALPOST=""
#				#FORMCLPRE=""
#				#FORMCLPOST=""
#				#PRELAB1=""
#				#POSTLAB1=""
#				#PRELAB2=""
#				#POSTLAB2=""
#				#PRELAB3=""
#				#POSTLAB3=""
#			
#				# TDE-kdialog does not support custom buttons.
#				if [ "$(kdialog --version | grep -a Qt | grep -aEo "[0-9]" | head -n 1)" -ge 4 ] || [ "$(kdialog --version | grep -aEi kdialog | grep -aEo "[0-9]" | head -n 1)" -gt 1 ] ; then
#					YES="--yes-label"
#					NO="--no-label"
#					OK="--continue-label"
#					CONTINUE="--continue-label"
#					CANCEL="--cancel-label"
#					EXTRABUTTON="--cancel-label"
#				fi
		
			else
		
				true
		
			fi
		
		if [ "$DIALOG" != "" ] ; then break ; fi
		
		fi

	done

fi

if [ "$DIALOG" = "" ] ; then
	echo $"ERROR: No supported dialog is installed. $TITLE cannot continue."
	exit 1
fi


### NOTE ########################################

# Yes, we set language and keyboard immediately after setting $DIALOG and before anything else, so that the messages are in a language understandable by the user (pica1 is used in non-live systems so the user does not choose the language at startup). And yes, we keep an identical copy in its usual place, because it just asks a couple of questions for confirmation.


### BASICFUN ########################################

ESP=$(printf '\302\240')

# architecture of the running kernel:

if [ "$(uname -mr | grep -aEi 'amd64|x86_64|x86-64' )" != "" ] ; then SYSARC="amd64" ; fi
if [ "$(uname -mr | grep -aEi 'armel|iop32x|ixp4xx|kirkwood|marvell|mv78xx0|orion5x|rpi|versatile|arm' )" != "" ] ; then SYSARC="armel" ; fi
if [ "$(uname -mr | grep -aEi 'armhf|armmp|mx5|omap|vexpress|armv' )" != "" ] ; then SYSARC="armhf" ; fi
if [ "$(uname -mr | grep -aEi 'arm64|aarch64' )" != "" ] ; then SYSARC="arm64" ; fi
if [ "$(uname -mr | grep -aEi '386|486|586|686|x86_32|x86-32' )" != "" ] ; then SYSARC="i386" ; fi
if [ "$(uname -mr | grep -aEi 'itanium|mckinley|ia64' )" != "" ] ; then SYSARC="ia64" ; fi
if [ "$(uname -mr | grep -aEi 'loong64|loongarch64' )" != "" ] ; then SYSARC="loong64" ; fi
if [ "$(uname -mr | grep -aEi 'bcm91|ip22|ip32|malta|mips|octeon' )" != "" ] ; then SYSARC="mips" ; fi
if [ "$(uname -mr | grep -aEi 'loongson|malta|mips64|octeon' )" != "" ] ; then SYSARC="mips64el" ; fi
if [ "$(uname -mr | grep -aEi 'loongson|bcm91|cobalt|malta|mips32|mipsel|octeon' )" != "" ] ; then SYSARC="mipsel" ; fi
if [ "$(uname -mr | grep -aEi 'powerpc|powerpc64|ppc|ppc64' )" != "" ] ; then SYSARC="powerpc" ; fi
if [ "$(uname -mr | grep -aEi 'powerpc64le|ppc64el|ppc64le' )" != "" ] ; then SYSARC="ppc64el" ; fi
if [ "$(uname -mr | grep -aEi 'riscv64|rv64' )" != "" ] ; then SYSARC="riscv64" ; fi
if [ "$(uname -mr | grep -aEi 's390x' )" != "" ] ; then SYSARC="s390x" ; fi
if [ "$(uname -mr | grep -aEi 'sparc' )" != "" ] ; then SYSARC="sparc" ; fi
if [ "$(uname -mr | grep -aEi 'sparc64' )" != "" ] ; then SYSARC="sparc64" ; fi


### LANGUAGE ########################################

### set language

# dpkg-reconfigure locales  # if the 'locales' package is installed

#	# a lot of output... temporal turn off logging
#	if [ "$DEBUG" = "Y" ] ; then
#	set +xv
#	fi

LANGCOD=$(locale | grep -aEi 'LANG' | sed 's|.*=||g' | sort -r | head -n 1 )

# xx_XX
LANGNAME=$(grep -aEi ^\"$(locale | grep -aEi 'LANG' | sed 's|.*=||g' | sort -r | head -n 1 | cut -d '.' -f 1 | cut -d '@' -f 1 | cut -d ':' -f 1 )\" $LIBDEP/langcod.list | head -n 1 | awk -F "\t" '{print $2}' | sed "s|_|$ESP|g" | sed 's|"||g' )
if [ "$LANGNAME" = "" ] ; then
# xx
LANGNAME=$(grep -aEi ^\"$(locale | grep -aEi 'LANG' | sed 's|.*=||g' | sort -r | head -n 1 | cut -d '.' -f 1 | cut -d '@' -f 1 | cut -d ':' -f 1 | sed 's|_.*||g' )\" $LIBDEP/langcod.list | head -n 1 | awk -F "\t" '{print $2}' | sed "s|_|$ESP|g" | sed 's|"||g' )
fi
if [ "$LANGNAME" = "" ] ; then
LANGNAME="$LANGCOD"
fi

#	# after a lot of output... turn on logging
#	if [ "$DEBUG" = "Y" ] ; then
#	exec > >(tee -a "$ERRORLOG") 2>&1 ; set -xv
#	fi

$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"The current language of the system is $LANGNAME ( $LANGCOD ).\n\nDo you want to change it?\n" $H $W

# If change language is Yes
if [ "$?" -eq 0 ] ; then

gen_langlist () {

#	# a lot of output... temporal turn off logging
#	if [ "$DEBUG" = "Y" ] ; then
#	set +xv
#	fi

# xx_XX
LANGLISTi=$(grep -aEi ^\"$(echo $i)\" $LIBDEP/langcod.list | head -n 1 | awk -F "\t" '{print $2}' | sed "s|_|$ESP|g" | sed 's|"||g' )
if [ "$LANGLISTi" = "" ] ; then
# xx
LANGLISTi=$(grep -aEi ^\"$(echo $i | sed "s|_.*||g")\" $LIBDEP/langcod.list | head -n 1 | awk -F "\t" '{print $2}' | sed "s|_|$ESP|g" | sed 's|"||g' )
fi
if [ "$LANGLISTi" = "" ] ; then
LANGLISTi="$i"
fi
echo "$LANGLISTi"

#	# after a lot of output... turn on logging
#	if [ "$DEBUG" = "Y" ] ; then
#	exec > >(tee -a "$ERRORLOG") 2>&1 ; set -xv
#	fi
}

lang_sel () {

	$DIALOG $WICON $WTITLE "$TITLE" $OK " " $WAIT  $WTEXT $"Please wait..." $H $W &
	PIDDIALOGLANG=$( echo $! )

#	# a lot of output... temporal turn off logging
#	if [ "$DEBUG" = "Y" ] ; then
#	set +xv
#	fi

LANGLIST=$(locale -a | cut -d '.' -f 1 | cut -d '@' -f 1 | cut -d ':' -f 1 | cut -d ' ' -f 1 | sort -u | while read i ; do printf "$i.UTF-8""\t" ; gen_langlist ; done)
if [ "$LANGLIST" = "" ] ; then
LANGLIST=$(ls /usr/lib/locale/ | cut -d '.' -f 1 | cut -d '@' -f 1 | cut -d ':' -f 1 | cut -d ' ' -f 1 | sort -u | while read i ; do printf "$i.UTF-8""\t" ; gen_langlist ; done)
fi

#	# after a lot of output... turn on logging
#	if [ "$DEBUG" = "Y" ] ; then
#	exec > >(tee -a "$ERRORLOG") 2>&1 ; set -xv
#	fi
	kill $PIDDIALOGLANG 2>/dev/null

PRE_LANGSEL=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"Please select a language:" $H $W $LH $COLUMN $COLUMN $LANGLIST | head -n 1 )

	if [ "$?" -ne 0 ] ; then
		exit 0
	fi

	if [ "$PRE_LANGSEL" = "" ] ; then
		REFUN=lang_sel
		input_error ; return
	fi

LANGSEL=$(echo "$PRE_LANGSEL" | awk '{print $1}' )

#echo "LANGSEL=$LANGSEL" | tee -a /tmp/iivar

# Generate locale if it does not exist
if [ ! -e "/usr/lib/locale/$(echo $LANGSEL | sed 's|\.UTF-8|.utf8|g')/LC_MESSAGES/" ] ; then
	if [ -e /etc/locale.gen ] ; then
		CHARSET="$(echo $LANGSEL | cut -s -d '.' -f 2 | cut -d '@' -f 1)"
		if [ "$CHARSET" = "" ] ; then
			CHARSET="UTF-8"
		fi
		sed -i -e "s|# $LANGSEL $CHARSET|$LANGSEL $CHARSET|" /etc/locale.gen
	fi
	locale-gen --keep-existing 2>&1
fi

}

lang_sel

# If change language is Yes
fi

if [ "$LANGSEL" != "" ] ; then

#update-locale LANG=$LANGSEL LANGUAGE=$LANGSEL locales=$LANGSEL
cat > /etc/default/locale <<EOF
LANG=$LANGSEL
LANGUAGE=$LANGSEL
locales=$LANGSEL
EOF

export LC_ALL=$LANGSEL
export LANG=$LANGSEL
export LANGUAGE=$LANGSEL
export locales=$LANGSEL
export LC_ALL=

fi


### TERMINAL SELECTION ########################################

if [ "$G" != "N" ] && [ "$(command -v lxterminal sakura xfce4-terminal)" = "" ] ; then $DIALOG $WICON $WTITLE "$TITLE" $WM    $WTEXT $"WARNING: Neither 'lxterminal', nor 'sakura' nor 'xfce4-terminal' are installed, $TITLE might fail." $H $W ; fi

TERMINAL () {
if [ "$G" = "N" ] ; then
	if [ "$TT" != "$TITLE" ] ; then echo "$TT" ; sleep 1 ; fi
	$COM
else
	if [ "$(command -v sakura)" != "" ] ; then
#		sakura -t "$TT" -e "$COM"  # https://bugs.debian.org/782396
		sakura -t "$TT" -x "$COM"  # sakura '-e' bug en Debian 13 "Trixie": Segment violation
	elif [ "$(command -v lxterminal)" != "" ] ; then
		lxterminal -t "$TT" -e "$COM"
	elif [ "$(command -v xfce4-terminal)" != "" ] ; then
		xfce4-terminal -T "$TT" -e "$COM"
	else
		x-terminal-emulator -t "$TT" -e "$COM"
	fi
fi
}


### set kbmap

# dpkg-reconfigure keyboard-configuration

#	# a lot of output... temporal turn off logging
#	if [ "$DEBUG" = "Y" ] ; then
#	set +xv
#	fi

KBCOD=$(setxkbmap -query | grep -aEi "^layout" | sed "s|.*=||g" | awk '{print $NF}' | head -n 1 | tr "[A-Z]" "[a-z]")
if [ "$KBCOD" = "" ] ; then KBCOD=$(cat /etc/default/keyboard | grep -a 'XKBLAYOUT=' | sed "s|.*=||g" | sed 's|"||g' | tr "[A-Z]" "[a-z]") ; fi
if [ "$KBCOD" = "" ] ; then KBCOD=$(env | grep -aEi "^LANG=" | sed "s|.*=||g" | sed 's|"||g' | cut -d '.' -f 1 | cut -d '@' -f 1 | cut -d ':' -f 1 | cut -d '_' -f 2 | sed 's|"||g' | tr "[A-Z]" "[a-z]") ; fi

if [ "$KBCOD" != "" ] ; then
	KBNAME=$(grep -aEi ^\"$(echo $KBCOD)\" $LIBDEP/kbcod.list | head -n 1 | awk -F "\t" '{print $2}' | sed "s|_|$ESP|g" | sed 's|"||g')
	if [ "$KBNAME" = "" ] ; then
		KBNAME="$KBCOD"
	fi
else
	echo $"ERROR" KBCOD="$KBCOD"
fi

#	# after a lot of output... turn on logging
#	if [ "$DEBUG" = "Y" ] ; then
#	exec > >(tee -a "$ERRORLOG") 2>&1 ; set -xv
#	fi

$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"The current keyboard map is $KBNAME ( $KBCOD ).\n\nDo you want to change it?\n" $H $W

# If change kbmap is Yes
if [ "$?" -eq 0 ] ; then

gen_kblist () {
KBLISTi=$(grep -aEi ^\"$(echo $i)\" $LIBDEP/kbcod.list | head -n 1 | awk -F "\t" '{print $2}' | sed "s|_|$ESP|g" | sed 's|"||g')
if [ "$KBLISTi" = "" ] ; then
	if [ "$(printf $i | wc -m)" -gt 2 ] ; then
		KBLISTi="(-)"
	else
		KBLISTi="$i"
	fi
fi
echo "$KBLISTi"
}

kb_sel () {

	$DIALOG $WICON $WTITLE "$TITLE" $OK " " $WAIT  $WTEXT $"Please wait..." $H $W &
	PIDDIALOGKB=$( echo $! )

#	# a lot of output... temporal turn off logging
#	if [ "$DEBUG" = "Y" ] ; then
#	set +xv
#	fi

# section 'Layout' in  /usr/share/console-setup/KeyboardNames.pl  /usr/share/doc/keyboard-configuration/xorg.lst  /usr/share/X11/xkb/rules/base.lst  ( /usr/share/doc/keyboard-configuration/xorg.lst -> ../../X11/xkb/rules/xorg.lst )

KBLIST=$(ls -p /usr/share/X11/xkb/symbols | grep -av '/' | while read i ; do printf "$i" ; printf "\t" ; gen_kblist ; done)

#	# after a lot of output... turn on logging
#	if [ "$DEBUG" = "Y" ] ; then
#	exec > >(tee -a "$ERRORLOG") 2>&1 ; set -xv
#	fi
	kill $PIDDIALOGKB 2>/dev/null

#KBSEL=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"Please select a keyboard map:" $H $W $LH $COLUMN $COLUMN  "es" $"Spanish" "gb" $"English GB" "us" $"English USA" $KBLIST | head -n 1 )

PRE_KBSEL=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"Please select a keyboard map:\n\n(You must not select a '(-)' option unless you are clear about what you do.)\n" $H $W $LH $COLUMN $COLUMN $KBLIST $"Advanced options" " " | head -n 1 )

	if [ "$?" -ne 0 ] ; then
		exit 0
	fi

	if [ "$PRE_KBSEL" = "" ] ; then
		REFUN=kb_sel
		input_error ; return
	fi

	if [ "$PRE_KBSEL" = $"Advanced options" ] ; then
		exec >/dev/tty
		TT=$"$TITLE" ; COM="dpkg-reconfigure keyboard-configuration" ; TERMINAL
		if [ "$DEBUG" != "N" ] ; then
			exec > >(tee -a "$ERRORLOG") 2>&1
		fi
		PRE_KBSEL=$(cat /etc/default/keyboard | grep -a 'XKBLAYOUT=' | sed "s|.*=||g" | sed 's|"||g' | tr "[A-Z]" "[a-z]")
	fi

# Test without modifying /etc/default/keyboard

	if [ "$(command -v setupcon)" != "" ] ; then cp --remove-destination /etc/default/keyboard ~/.keyboard ; sed -i "s|^XKBLAYOUT=.*|XKBLAYOUT=$PRE_KBSEL|g" ~/.keyboard ; setupcon -k ; fi
	if [ "$(command -v setxkbmap)" != "" ] ; then setxkbmap $PRE_KBSEL ; fi
	
	TEST_KBSEL=$($DIALOG $WICON $WTITLE "$TITLE" $WRITE $WTEXT $"Please test the new keyboard map by typing for example hyphen, underscore, slash, parentheses, brackets, braces, comma, point, semicolon, colon, single quote, double quote, less than, greater than,...\n\nPress 'Yes/OK' to confirm or 'No/Cancel' to choose another keyboard map.\n" $H $W)

	if [ "$?" -ne 0 ] ; then
		kb_sel ; return
	fi
	
	if [ "$(command -v setupcon)" != "" ] ; then rm -f ~/.keyboard ; fi

KBSEL=$(echo "$PRE_KBSEL" | awk '{print $1}' )

#echo "KBSEL=$KBSEL" | tee -a /tmp/iivar

}

kb_sel

# If change kbmap is Yes
fi

if [ "$KBSEL" != "" ] ; then
sed -i "s|^XKBLAYOUT=.*|XKBLAYOUT=$KBSEL|g" /etc/default/keyboard
#if [ "$(command -v loadkeys)"  != "" ] ; then loadkeys $KBSEL ; fi  # loadkeys uses another keymap nomenclature
udevadm trigger --subsystem-match=input --action=change
if [ "$(command -v setupcon)" != "" ] ; then setupcon -k ; fi
if [ "$(command -v setxkbmap)" != "" ] ; then setxkbmap $KBSEL ; fi
fi


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

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


### BASICFUN ########################################

clean () {
if [ "$DEBUG" = "Y" ] ; then set +xv ; fi
if [ -n "$NEWUSERPASS" ] ; then  sed -i "s|$NEWUSERPASS|__NEWUSERPASS__|g" $ERRORLOG  ; fi
if [ -n "$NEWROOTPASS" ] ; then  sed -i "s|$NEWROOTPASS|__NEWROOTPASS__|g" $ERRORLOG  ; fi
if [ -n "$GUESTPASS"   ] ; then  sed -i "s|$GUESTPASS|__GUESTPASS__|g"     $ERRORLOG  ; fi
exec > >(tee -a "$ERRORLOG") 2>&1 ; if [ "$DEBUG" = "Y" ] ; then set -xv ; fi
unset NEWUSERNAME NEWUSERREALNAME NEWUSERPASS NEWROOTPASS GUESTNAME GUESTUSERNAME GUESTREALNAME GUESTPASS
}

check_exit () {

TAILERRORLOG=$(cat "$ERRORLOG" | grep -aE "[a-zA-Z0-9\=\[]" | tail -n 10 )

echo $(date +%Y-%m-%d_%H:%M:%S)

clean

#if [ "$(cat /etc/passwd | grep -aE ^$(whoami): | cut -d ':' -f 3 )" -eq 0 ] ; then
if [ "$(id -u)" -eq 0 ] && [ "$DEBUG" = "Y" ] ; then
	RECERRORLOG="$ERRORLOG"
	for i in $(cat /etc/passwd | awk -F ':' '{print $3,$1}' | sort -n | grep -aEi "00[0-9] " | awk '{print $2}') ; do AUSER=$(users | sed 's| |\n|g' | grep -aE "^$i$" | head -n 1) ; if [ "$AUSER" != "" ] ; then
		HOMEERRORLOG=/home/$i/.${CNAME}.log
		RECERRORLOG="$RECERRORLOG $HOMEERRORLOG "
		cp -v --remove-destination $ERRORLOG $HOMEERRORLOG
		if [ "$(id -nu $i)" != "" ] ; then chown $(id -nu $i):$(id -ng $i) $HOMEERRORLOG ; else chown 1000:1000 $HOMEERRORLOG ; fi
		chmod 600 $HOMEERRORLOG ; if [ "$(stat -c %U $HOMEERRORLOG)" != "$i" ] ; then chmod 666 $HOMEERRORLOG ; fi
		break
	fi ; done
fi

$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"Stop due to error.\n\n$TAILERRORLOG\n" $H $W

exit 1

}

# "try again or exit" dialog window
input_error () {

echo $(date +%Y-%m-%d_%H:%M:%S)

$DIALOG $WICON $WTITLE "$TITLE" $WYN   $WTEXT $"Something went wrong.\n\nDo you want to try again?" $H $W

if [ "$?" -ne 0 ] ; then
	clean
	exit 1
else
	$REFUN
fi

}


### ALREADY RUNNING ########################################

if [ "$CNAME" != "" ] && [ "$(lsof /usr/bin/$CNAME 2>>$ERRORLOG | grep -ai -c $CNAME)" -gt 1 ] ; then

	REPE=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"$CNAME seems to be already working. Having $CNAME working multiple times at the same time may cause problems.\n\nStop them all is recommended.\n\nPlease select an option:" $H $W $LH $COLUMN $COLUMN \
	$"Continue" " " \
	$"Stop now" " " \
	$"Stop them all" " " \
	| head -n 1 )

	if [ "$?" -ne 0 ] || [ "$REPE" = "" ] ; then
		exit 0
	fi

	case $REPE in

		$"Continue" )
			true
		;;

		$"Stop now" )
			exit 0
		;;

		$"Stop them all" )
			clean
			kill $(echo $(ps aux | grep -a "$CNAME" | grep -av 'grep ' | awk '{print $2}'))
		;;

	esac

fi


### WELCOME ########################################

if [ "$WELCOME" != "N" ] ; then

$DIALOG $WICON $WTITLE "$TITLE" $INFO  $WTEXT $"Welcome to $TITLE.\n\n$TITLE is a tool to perform the initial customization of systems not installed using Pica-II.\n\nUsing $TITLE is optional, only if you want to change users, language, keyboard and time zone. It should normally be used only once (the first time the system is used after copying it using Pica-IE) and not on systems installed using Pica-II.\n\n$TITLE is libre/free software, licensed according to 'GNU AGPL version 3.0'.\n\nIt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.\n\nMore information at www.picalibre.org\n" $H $W

if [ "$?" -ne 0 ] ; then
	exit 0
fi

fi


### USER CHECK ########################################

AUSER=$(cat /etc/passwd | awk -F ':' '{print $3,$1}' | sort -n | grep -aEi "00[0-9] " | awk '{print $2}' | head -n 1 )

USERNAMES_ACTIVE_1=$(top -n 1 -b | awk '{print $2}' | sort -u | grep -aE "^$AUSER$")
USERNAMES_ACTIVE_2=$(ps aux | awk '{print $1}' | sort -u | grep -aE "^$AUSER$")
USERNAMES_ACTIVE_3=$(users | sed 's| |\n|g' | grep -aE "^$AUSER$")
# don't delete active users.
if [ "$USERNAMES_ACTIVE_1" != "" ] || [ "$USERNAMES_ACTIVE_2" != "" ] || [ "$USERNAMES_ACTIVE_3" != "" ] ; then
	$DIALOG $WICON $WTITLE "$TITLE" $WYN   $WTEXT $"If the default user, who appears to be $AUSER, has an active session, you must log out of the user $AUSER and log in directly as 'root' (or as another user).\n\nDo you want to continue?\n" $H $W
	if [ "$?" -ne 0 ] ; then
		exit 0
	fi
fi


### CLOCK ########################################

# Set /etc/timezone

#DET_LOCALE=$(locale | grep -aE 'TIME' | grep -aE -o '\".*\"'| sed 's|"||g')
#if [ "$DET_LOCALE" != "en_GB.UTF-8" ] ; then
#	DIF_LOCALE="English - Great Britain"
#elif [ "$DET_LOCALE" != "en_US.UTF-8" ] ; then
#	DIF_LOCALE="English - USA"
#elif [ "$DET_LOCALE" != "es_ES.UTF-8" ] ; then
#	DIF_LOCALE="Español - España"
#else
#	DIF_LOCALE="Custom locale"
#fi

CONTINENT=$(cat /etc/timezone | cut -d '/' -f 1 )
CAPITAL=$(cat /etc/timezone | cut -d '/' -f 2 )

if [ "$CONTINENT" = "" ] || [ "$CAPITAL" = "" ] ; then
	$DIALOG $WICON $WTITLE "$TITLE" $INFO  $WTEXT $"Now a terminal dialog will be opened to set the local time." $H $W
	exec >/dev/tty
	TT=$"Reconfigure local time" ; COM="dpkg-reconfigure tzdata" ; TERMINAL
	if [ "$DEBUG" != "N" ] ; then
		exec > >(tee -a "$ERRORLOG") 2>&1
	fi
else
	$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"The current time zone of the system is continent: $CONTINENT, capital: $CAPITAL \n\nDo you want to change it?\n" $H $W
	if [ "$?" -eq 0 ] ; then
	exec >/dev/tty
	TT=$"Reconfigure local time" ; COM="dpkg-reconfigure tzdata" ; TERMINAL
	if [ "$DEBUG" != "N" ] ; then
		exec > >(tee -a "$ERRORLOG") 2>&1
	fi
	fi
fi


### LANGUAGE ########################################

### set language

# dpkg-reconfigure locales  # if the 'locales' package is installed

#	# a lot of output... temporal turn off logging
#	if [ "$DEBUG" = "Y" ] ; then
#	set +xv
#	fi

LANGCOD=$(locale | grep -aEi 'LANG' | sed 's|.*=||g' | sort -r | head -n 1 )

# xx_XX
LANGNAME=$(grep -aEi ^\"$(locale | grep -aEi 'LANG' | sed 's|.*=||g' | sort -r | head -n 1 | cut -d '.' -f 1 | cut -d '@' -f 1 | cut -d ':' -f 1 )\" $LIBDEP/langcod.list | head -n 1 | awk -F "\t" '{print $2}' | sed "s|_|$ESP|g" | sed 's|"||g' )
if [ "$LANGNAME" = "" ] ; then
# xx
LANGNAME=$(grep -aEi ^\"$(locale | grep -aEi 'LANG' | sed 's|.*=||g' | sort -r | head -n 1 | cut -d '.' -f 1 | cut -d '@' -f 1 | cut -d ':' -f 1 | sed 's|_.*||g' )\" $LIBDEP/langcod.list | head -n 1 | awk -F "\t" '{print $2}' | sed "s|_|$ESP|g" | sed 's|"||g' )
fi
if [ "$LANGNAME" = "" ] ; then
LANGNAME="$LANGCOD"
fi

#	# after a lot of output... turn on logging
#	if [ "$DEBUG" = "Y" ] ; then
#	exec > >(tee -a "$ERRORLOG") 2>&1 ; set -xv
#	fi

$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"The current language of the system is $LANGNAME ( $LANGCOD ).\n\nDo you want to change it?\n" $H $W

# If change language is Yes
if [ "$?" -eq 0 ] ; then

gen_langlist () {

#	# a lot of output... temporal turn off logging
#	if [ "$DEBUG" = "Y" ] ; then
#	set +xv
#	fi

# xx_XX
LANGLISTi=$(grep -aEi ^\"$(echo $i)\" $LIBDEP/langcod.list | head -n 1 | awk -F "\t" '{print $2}' | sed "s|_|$ESP|g" | sed 's|"||g' )
if [ "$LANGLISTi" = "" ] ; then
# xx
LANGLISTi=$(grep -aEi ^\"$(echo $i | sed "s|_.*||g")\" $LIBDEP/langcod.list | head -n 1 | awk -F "\t" '{print $2}' | sed "s|_|$ESP|g" | sed 's|"||g' )
fi
if [ "$LANGLISTi" = "" ] ; then
LANGLISTi="$i"
fi
echo "$LANGLISTi"

#	# after a lot of output... turn on logging
#	if [ "$DEBUG" = "Y" ] ; then
#	exec > >(tee -a "$ERRORLOG") 2>&1 ; set -xv
#	fi
}

lang_sel () {

	$DIALOG $WICON $WTITLE "$TITLE" $OK " " $WAIT  $WTEXT $"Please wait..." $H $W &
	PIDDIALOGLANG=$( echo $! )

#	# a lot of output... temporal turn off logging
#	if [ "$DEBUG" = "Y" ] ; then
#	set +xv
#	fi

LANGLIST=$(locale -a | cut -d '.' -f 1 | cut -d '@' -f 1 | cut -d ':' -f 1 | cut -d ' ' -f 1 | sort -u | while read i ; do printf "$i.UTF-8""\t" ; gen_langlist ; done)
if [ "$LANGLIST" = "" ] ; then
LANGLIST=$(ls /usr/lib/locale/ | cut -d '.' -f 1 | cut -d '@' -f 1 | cut -d ':' -f 1 | cut -d ' ' -f 1 | sort -u | while read i ; do printf "$i.UTF-8""\t" ; gen_langlist ; done)
fi

#	# after a lot of output... turn on logging
#	if [ "$DEBUG" = "Y" ] ; then
#	exec > >(tee -a "$ERRORLOG") 2>&1 ; set -xv
#	fi
	kill $PIDDIALOGLANG 2>/dev/null

PRE_LANGSEL=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"Please select a language:" $H $W $LH $COLUMN $COLUMN $LANGLIST | head -n 1 )

	if [ "$?" -ne 0 ] ; then
		exit 0
	fi

	if [ "$PRE_LANGSEL" = "" ] ; then
		REFUN=lang_sel
		input_error ; return
	fi

LANGSEL=$(echo "$PRE_LANGSEL" | awk '{print $1}' )

#echo "LANGSEL=$LANGSEL" | tee -a /tmp/iivar

# Generate locale if it does not exist
if [ ! -e "/usr/lib/locale/$(echo $LANGSEL | sed 's|\.UTF-8|.utf8|g')/LC_MESSAGES/" ] ; then
	if [ -e /etc/locale.gen ] ; then
		CHARSET="$(echo $LANGSEL | cut -s -d '.' -f 2 | cut -d '@' -f 1)"
		if [ "$CHARSET" = "" ] ; then
			CHARSET="UTF-8"
		fi
		sed -i -e "s|# $LANGSEL $CHARSET|$LANGSEL $CHARSET|" /etc/locale.gen
	fi
	locale-gen --keep-existing 2>&1
fi

}

lang_sel

# If change language is Yes
fi

if [ "$LANGSEL" != "" ] ; then

#update-locale LANG=$LANGSEL LANGUAGE=$LANGSEL locales=$LANGSEL
cat > /etc/default/locale <<EOF
LANG=$LANGSEL
LANGUAGE=$LANGSEL
locales=$LANGSEL
EOF

export LC_ALL=$LANGSEL
export LANG=$LANGSEL
export LANGUAGE=$LANGSEL
export locales=$LANGSEL
export LC_ALL=

fi


### set kbmap

# dpkg-reconfigure keyboard-configuration

#	# a lot of output... temporal turn off logging
#	if [ "$DEBUG" = "Y" ] ; then
#	set +xv
#	fi

KBCOD=$(setxkbmap -query | grep -aEi "^layout" | sed "s|.*=||g" | awk '{print $NF}' | head -n 1 | tr "[A-Z]" "[a-z]")
if [ "$KBCOD" = "" ] ; then KBCOD=$(cat /etc/default/keyboard | grep -a 'XKBLAYOUT=' | sed "s|.*=||g" | sed 's|"||g' | tr "[A-Z]" "[a-z]") ; fi
if [ "$KBCOD" = "" ] ; then KBCOD=$(env | grep -aEi "^LANG=" | sed "s|.*=||g" | sed 's|"||g' | cut -d '.' -f 1 | cut -d '@' -f 1 | cut -d ':' -f 1 | cut -d '_' -f 2 | sed 's|"||g' | tr "[A-Z]" "[a-z]") ; fi

if [ "$KBCOD" != "" ] ; then
	KBNAME=$(grep -aEi ^\"$(echo $KBCOD)\" $LIBDEP/kbcod.list | head -n 1 | awk -F "\t" '{print $2}' | sed "s|_|$ESP|g" | sed 's|"||g')
	if [ "$KBNAME" = "" ] ; then
		KBNAME="$KBCOD"
	fi
else
	echo $"ERROR" KBCOD="$KBCOD"
fi

#	# after a lot of output... turn on logging
#	if [ "$DEBUG" = "Y" ] ; then
#	exec > >(tee -a "$ERRORLOG") 2>&1 ; set -xv
#	fi

$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"The current keyboard map is $KBNAME ( $KBCOD ).\n\nDo you want to change it?\n" $H $W

# If change kbmap is Yes
if [ "$?" -eq 0 ] ; then

gen_kblist () {
KBLISTi=$(grep -aEi ^\"$(echo $i)\" $LIBDEP/kbcod.list | head -n 1 | awk -F "\t" '{print $2}' | sed "s|_|$ESP|g" | sed 's|"||g')
if [ "$KBLISTi" = "" ] ; then
	if [ "$(printf $i | wc -m)" -gt 2 ] ; then
		KBLISTi="(-)"
	else
		KBLISTi="$i"
	fi
fi
echo "$KBLISTi"
}

kb_sel () {

	$DIALOG $WICON $WTITLE "$TITLE" $OK " " $WAIT  $WTEXT $"Please wait..." $H $W &
	PIDDIALOGKB=$( echo $! )

#	# a lot of output... temporal turn off logging
#	if [ "$DEBUG" = "Y" ] ; then
#	set +xv
#	fi

# section 'Layout' in  /usr/share/console-setup/KeyboardNames.pl  /usr/share/doc/keyboard-configuration/xorg.lst  /usr/share/X11/xkb/rules/base.lst  ( /usr/share/doc/keyboard-configuration/xorg.lst -> ../../X11/xkb/rules/xorg.lst )

KBLIST=$(ls -p /usr/share/X11/xkb/symbols | grep -av '/' | while read i ; do printf "$i" ; printf "\t" ; gen_kblist ; done)

#	# after a lot of output... turn on logging
#	if [ "$DEBUG" = "Y" ] ; then
#	exec > >(tee -a "$ERRORLOG") 2>&1 ; set -xv
#	fi
	kill $PIDDIALOGKB 2>/dev/null

#KBSEL=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"Please select a keyboard map:" $H $W $LH $COLUMN $COLUMN  "es" $"Spanish" "gb" $"English GB" "us" $"English USA" $KBLIST | head -n 1 )

PRE_KBSEL=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"Please select a keyboard map:\n\n(You must not select a '(-)' option unless you are clear about what you do.)\n" $H $W $LH $COLUMN $COLUMN $KBLIST $"Advanced options" " " | head -n 1 )

	if [ "$?" -ne 0 ] ; then
		exit 0
	fi

	if [ "$PRE_KBSEL" = "" ] ; then
		REFUN=kb_sel
		input_error ; return
	fi

	if [ "$PRE_KBSEL" = $"Advanced options" ] ; then
		exec >/dev/tty
		TT=$"$TITLE" ; COM="dpkg-reconfigure keyboard-configuration" ; TERMINAL
		if [ "$DEBUG" != "N" ] ; then
			exec > >(tee -a "$ERRORLOG") 2>&1
		fi
		PRE_KBSEL=$(cat /etc/default/keyboard | grep -a 'XKBLAYOUT=' | sed "s|.*=||g" | sed 's|"||g' | tr "[A-Z]" "[a-z]")
	fi

# Test without modifying /etc/default/keyboard

	if [ "$(command -v setupcon)" != "" ] ; then cp --remove-destination /etc/default/keyboard ~/.keyboard ; sed -i "s|^XKBLAYOUT=.*|XKBLAYOUT=$PRE_KBSEL|g" ~/.keyboard ; setupcon -k ; fi
	if [ "$(command -v setxkbmap)" != "" ] ; then setxkbmap $PRE_KBSEL ; fi
	
	TEST_KBSEL=$($DIALOG $WICON $WTITLE "$TITLE" $WRITE $WTEXT $"Please test the new keyboard map by typing for example hyphen, underscore, slash, parentheses, brackets, braces, comma, point, semicolon, colon, single quote, double quote, less than, greater than,...\n\nPress 'Yes/OK' to confirm or 'No/Cancel' to choose another keyboard map.\n" $H $W)

	if [ "$?" -ne 0 ] ; then
		kb_sel ; return
	fi
	
	if [ "$(command -v setupcon)" != "" ] ; then rm -f ~/.keyboard ; fi

KBSEL=$(echo "$PRE_KBSEL" | awk '{print $1}' )

#echo "KBSEL=$KBSEL" | tee -a /tmp/iivar

}

kb_sel

# If change kbmap is Yes
fi

if [ "$KBSEL" != "" ] ; then
sed -i "s|^XKBLAYOUT=.*|XKBLAYOUT=$KBSEL|g" /etc/default/keyboard
#if [ "$(command -v loadkeys)"  != "" ] ; then loadkeys $KBSEL ; fi  # loadkeys uses another keymap nomenclature
udevadm trigger --subsystem-match=input --action=change
if [ "$(command -v setupcon)" != "" ] ; then setupcon -k ; fi
if [ "$(command -v setxkbmap)" != "" ] ; then setxkbmap $KBSEL ; fi
fi


### USERS AND PASSWORDS ########################################

AUSER=$(cat /etc/passwd | awk -F ':' '{print $3,$1}' | sort -n | grep -aEi "00[0-9] " | awk '{print $2}' | head -n 1 )

$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"The default user appears to be $AUSER \n\nDo you want to change the user or passwords?\n" $H $W

# If change users is Yes
if [ "$?" -eq 0 ] ; then

$DIALOG $WICON $WTITLE "$TITLE" $INFO  $WTEXT $"For a good system security, you must configure at least two users: \n\n* An administrator user (named 'root') with SuperUser powers, whose password is requested when somebody attempts to do an action that could jeopardize the security or stability of the system.\n\n* A normal or usual user (or several, one for each person who usually uses the computer), who do daily or routine activities with the computer.\n\nNow you will be asked for a username and password for the normal or usual user, and a password for the administrator user (named 'root') with SuperUser powers.\n\nPlease think them well (and keep them secret!).\n" $H $W

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

# 'su' (and GUI based on) defaults to 'root'. If the 'root' username is changed (1) or logging in as 'root' is disabled (2), then 'su' (and GUI based on) stops working: viable for servers, not for desktop. Changing the 'root' username can add little or nothing to the security because the new ID=0 username is easy to find for any logged-in user (3). Additionally, the 'root' password is easy to physically bypass (4) on directly used computers (5).
# (1) usermod -R /path/to/mounted/filesystem -l $NEWROOTNAME root  # -m -d /path/to/new/home  # If try it on the running system then error "usermod: user 'root' is currently used by process 1"
# (2) useradd -o -u 0 -g 0 -s $(command -v bash) -m -d /root/ $NEWROOTNAME ; printf "$NEWUSERPASS\n$NEWUSERPASS\n\n" | passwd $NEWROOTNAME ; usermod -s /bin/false root # /usr/sbin/nologin
# (3) On all native *NIX filesystems (also NFS and archive formats as tar), the ownership is stored as user and group (numeric) IDs (uid and gid) which is then mapped to resolve names using /etc/passwd and /etc/group. /etc/passwd requires 644 permissions in order to do userid (username <-> numeric ID) resolution. With 644 permissions, any user can find ID=0 username. If "chmod 600 /etc/passw*" then basic userid resolution stops working, so bash prompt will be "I have no name!@<hostname>#" and "ls -l" will show numeric ID instead of username in owner column. (Note that, in the rare case that there is a purely numeric username that matches an ID, then chown gives priority to the username, not the UID; it can be tested with 'id -u ID'.)
# (4) Changing the 'root' username allows to disable login as 'root' (for example in tty), but using the computer directly it is easy to physically bypass this via GRUB rescue, live system or plugging the internal disk into a laptop via (S)ATA-USB adapter (the first two can be avoided by disabling the option and setting some password in GRUB and in BIOS/EFI/u-boot/...). Note that, although it is not a 'root' username and password issue, disk encryption mitigates the vulnerabilities of directly used computers.
# (5) Login as 'root' should not be allowed in remote connections to the computer (e.g. ssh) in order to force double password (login username + su root) to elevate powers.

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

# set username
set_username () {
PRE_NEWUSERNAME=$($DIALOG $WICON $WTITLE "$TITLE" $WRITE $WTEXT $"Please write a username for the normal or usual user.\n\n(Letters and/or numbers only, hyphens and underscores are allowed as separators, but not spaces or other symbols, maximum length 32 characters.)\n" $H $W)

if [ "$?" -ne 0 ] ; then
	REFUN=set_username
	input_error ; return
fi

NEWUSERNAME=$(echo "$PRE_NEWUSERNAME" | sed 's| ||g')

# Check username conflict
CHECK_NEWUSERNAME=$(cat /etc/passwd /etc/group | awk -F ':' '{if ($3 < 1000 || $1 == "nobody" || $1 == "nogroup") print $1}' | grep -aE "^$NEWUSERNAME$")
if [ "$CHECK_NEWUSERNAME" != "" ] ; then
	$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"ERROR: The username matches an existing username." $H $W
	set_username ; return
fi

NC_NEWUSERNAME=$(printf "$NEWUSERNAME" | wc -m)
if [ "$NC_NEWUSERNAME" -gt 32 ] ; then
	$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"The username has $NC_NEWUSERNAME characters and the maximum length is 32 characters.\n\nPlease select other username." $H $W
	set_username
	return
fi

if [ "$NEWUSERNAME" = "" ] ; then
	REFUN=set_username
	input_error ; return
fi

}

set_username
#echo "NEWUSERNAME=\"$NEWUSERNAME\"" | tee -a /tmp/iivar


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

# set "user's full name"
set_userfullname () {
NEWUSERREALNAME=$($DIALOG $WICON $WTITLE "$TITLE" $WRITE $WTEXT $"Please write the new user's full name (you can use the same as before).\n\n(Spaces are allowed.)\n" $H $W $PREWRITE "$NEWUSERNAME")

	if [ "$?" -ne 0 ] ; then
	REFUN=set_userfullname
	input_error ; return
	fi

	if [ "$NEWUSERREALNAME" = "" ] ; then
	REFUN=set_userfullname
	input_error ; return
	fi
}

set_userfullname
#echo "NEWUSERREALNAME=\"$NEWUSERREALNAME\"" | tee -a /tmp/iivar


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

# set user password
set_userpass () {
NEWUSERPASS=$($DIALOG $WICON $WTITLE "$TITLE" $WRITE $WTEXT $"Please write a password for the normal or usual user.\n" $H $W)

	if [ "$?" -ne 0 ] ; then
	REFUN=set_userpass
	input_error ; return
	fi

	if [ "$NEWUSERPASS" = "" ] ; then
	REFUN=set_userpass
	input_error ; return
	fi
}

set_userpass
#echo "NEWUSERPASS=\"$NEWUSERPASS\"" | tee -a /tmp/iivar


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

# set root password
set_rootpass () {
NEWROOTPASS=$($DIALOG $WICON $WTITLE "$TITLE" $WRITE $WTEXT $"Please write a password for the administrator user (named 'root') with SuperUser powers.\n" $H $W)

	if [ "$?" -ne 0 ] ; then
	REFUN=set_rootpass
	input_error ; return
	fi

	if [ "$NEWROOTPASS" = "" ] ; then
	REFUN=set_rootpass
	input_error ; return
	fi
}

set_rootpass
#echo "NEWROOTPASS=\"$NEWROOTPASS\"" | tee -a /tmp/iivar


### OLD USER ########################################

OLDUSERNAME=$(cat /etc/passwd | awk -F ':' '{print $3,$1}' | sort -n | grep -aEi "00[0-9] " | head -n 1 | awk '{print $2}')

if [ "$OLDUSERNAME" != "" ] ; then

	echo "OLDUSERNAME=$OLDUSERNAME"
	OLDUSERGROUP=$OLDUSERNAME
	echo "OLDUSERGROUP=$OLDUSERNAME"

fi


### CONFIG USERS ########################################

# delete old user (including group and home)
if [ "$OLDUSERNAME" != "" ] ; then
	userdel -f -r $OLDUSERNAME
	rm -rf /home/$OLDUSERNAME
	groupdel $OLDUSERGROUP
fi

# create new user (including group)
groupadd -g 1000 $NEWUSERNAME
useradd -u 1000 -g 1000 -c "$NEWUSERREALNAME,,," -s $(command -v bash) -m $NEWUSERNAME
printf "$NEWUSERPASS\n$NEWUSERPASS\n\n" | passwd $NEWUSERNAME

# add to supplementary groups, checking first if they exist
if [ "$(dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2}' | sed "s|:.*||g" | grep -aEi "xserver-xorg|x11-session|x11-xserver|^cdm$|^console-tdm$|^edm$|^entrance$|^gdm$|^gdm3$|^kdm$|^kdm-trinity$|^lightdm$|^lxdm$|^ly$|^mdm$|^nodm$|^qingy$|^sddm$|^slim$|^tdm$|^tdm-trinity$|^wdm$|^xdm$")" != "" ] ; then
	GLIST="adm admin audio bluetooth cdrom cgroup crontab cups cupsadmin dialout dip disk fax floppy fuse input kvm lp lpadmin netdev plugdev powerdev pulse pulse-access pulse-rt qemu sambashare saned scanner ssh tape users vboxusers vlock video wireshark"
else
	GLIST="ssh users"
fi
for i in $GLIST ; do
	CHECKGROUP=$(cat /etc/group | awk -F ':' '{print $1}' | grep -aE "^$i$")
	if [ "$CHECKGROUP" != "" ] ; then
		echo "$NEWUSERNAME -> $i"
		usermod -a -G $i $NEWUSERNAME
	fi
done

if [ "$NEWROOTPASS" != "" ] ; then
	printf "$NEWROOTPASS\n$NEWROOTPASS\n\n" | passwd root
else
	passwd -l root
fi

# create nobody / nogroup if not exist
if [ "$(cat /etc/passwd | cut -d ':' -f 1 | grep -aE ^nobody$ )" = "" ] && [ "$(cat /etc/group | cut -d ':' -f 1 | grep -aE ^nogroup$ )" = "" ] ; then
	groupadd -g 65534 nogroup
	useradd -u 65534 -g 65534 nobody
fi

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

### Copy /etc/skel
cp -a --remove-destination /etc/skel/* /etc/skel/.[!.]* /etc/skel/..?* /root/
ls /home/ | grep -aiv 'lost+found' | while read i ; do cp -a --remove-destination /etc/skel/* /etc/skel/.[!.]* /etc/skel/..?* /home/"$i"/ ; done
cp -a --remove-destination /etc/skel/* /etc/skel/.[!.]* /etc/skel/..?* /home/$NEWUSERNAME/
if [ "$GUESTNAME" != "" ] ; then cp -a --remove-destination /etc/skel/* /etc/skel/.[!.]* /etc/skel/..?* /home/$GUESTNAME/ ; fi
#ls /home/ | grep -aiv 'lost+found' | while read i ; do cp -a --remove-destination /etc/skel/{,.[!.],..?}* /home/"$i"/ ; done
cp -a --remove-destination /root/.bashrcPICA /root/.bashrc
if [ "$SYSARC" = "amd64" ] || [ "$SYSARC" = "i386" ] || [ "$SYSARC" = "ia64" ] ; then sed -i -e '/presentation-mode/ s|false|true|g' -e '/dpms-enabled/ s|true|false|g' -e '/\("blank-on-ac"\|"dpms-on-ac-sleep"\|"dpms-on-ac-off"\)/ s|"[0-9]\+"|"0"|g' /root/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-power-manager.xml ; fi
ls /home/ | grep -aiv 'lost+found' | while read i ; do cd /home/"$i" ; cp -a --remove-destination .bashrcPICA .bashrc ; cd - ; done
if [ "$SYSARC" = "amd64" ] || [ "$SYSARC" = "i386" ] || [ "$SYSARC" = "ia64" ] ; then ls /home/ | grep -aiv 'lost+found' | while read i ; do cd /home/"$i" ; sed -i -e '/presentation-mode/ s|false|true|g' -e '/dpms-enabled/ s|true|false|g' -e '/\("blank-on-ac"\|"dpms-on-ac-sleep"\|"dpms-on-ac-off"\)/ s|"[0-9]\+"|"0"|g' .config/xfce4/xfconf/xfce-perchannel-xml/xfce4-power-manager.xml ; cd - ; done ; fi
cp -a --remove-destination /home/$NEWUSERNAME/.bashrcPICA /home/$NEWUSERNAME/.bashrc
if [ "$SYSARC" = "amd64" ] || [ "$SYSARC" = "i386" ] || [ "$SYSARC" = "ia64" ] ; then sed -i -e '/presentation-mode/ s|false|true|g' -e '/dpms-enabled/ s|true|false|g' -e '/\("blank-on-ac"\|"dpms-on-ac-sleep"\|"dpms-on-ac-off"\)/ s|"[0-9]\+"|"0"|g' /home/$NEWUSERNAME/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-power-manager.xml ; fi
if [ "$GUESTNAME" != "" ] ; then
	cp -a --remove-destination /home/$GUESTNAME/.bashrcPICA /home/$GUESTNAME/.bashrc
	if [ "$SYSARC" = "amd64" ] || [ "$SYSARC" = "i386" ] || [ "$SYSARC" = "ia64" ] ; then sed -i -e '/presentation-mode/ s|false|true|g' -e '/dpms-enabled/ s|true|false|g' -e '/\("blank-on-ac"\|"dpms-on-ac-sleep"\|"dpms-on-ac-off"\)/ s|"[0-9]\+"|"0"|g' /home/$GUESTNAME/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-power-manager.xml ; fi
fi
### Owners and permissions
ls /home/ | grep -aiv 'lost+found' | while read i ; do chown -R $(id -nu "$i"):$(id -ng "$i") /home/"$i" ; done
chown -R $(id -nu "$NEWUSERNAME"):$(id -ng "$NEWUSERNAME") /home/$NEWUSERNAME
if [ "$GUESTNAME" != "" ] ; then chown -R $(id -nu "$GUESTNAME"):$(id -ng "$GUESTNAME") /home/$GUESTNAME ; fi
find /home/$NEWUSERNAME/ -type f | while read i ; do chmod 600 "$i" ; done
find /home/$NEWUSERNAME/ -type d | while read i ; do chmod 700 "$i" ; done
if [ "$GUESTNAME" != "" ] ; then
	find /home/$GUESTNAME/ -type f | while read i ; do chmod 666 "$i" ; done
	find /home/$GUESTNAME/ -type d | while read i ; do chmod 777 "$i" ; done
	find /home/$GUESTNAME/ -maxdepth 1 | grep -a bashrc | while read i ; do sed -i '/umask 007/ s|.*|umask 000|g' "$i" ; done
fi
chown -R root:root /root
find /root/ -type f | while read i ; do chmod 600 "$i" ; done
find /root/ -type d | while read i ; do chmod 700 "$i" ; done
find /root/ -maxdepth 1 | grep -a bashrc | while read i ; do sed -i '/umask 007/ s|.*|umask 002\nchmod -R o= /root/|g' "$i" ; done

# delete 'debug by default'
if [ -e /etc/pica-global ] ; then rm -rf /etc/pica-global ; fi

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

# delete OLDUSERNAME in /etc/sudoers*
# might not be needed with live-config, it uses %sudo
if [ "$OLDUSERNAME" != "" ] ; then
	find /etc/ -type f | grep -a /etc/sudoers | while read i ; do
		if [ "$(cat "$i" | grep -a "$OLDUSERNAME")" != "" ] ; then
			sed -i "/^$OLDUSERNAME\t.*/d" "$i"
		fi
	done
fi

if [ -e /etc/sudoers.d/live ] ; then
	rm -rf /etc/sudoers.d/live
fi

#if [ "$FORCESUCONFIG" = "Y" ] ; then
	
	for OUSER in $NEWUSERNAME $GUESTNAME ; do
		for i in /home/$OUSER/.trinity/share/config/kdesurc /home/$OUSER/.trinity/share/config/tdesurc /home/$OUSER/.kde/share/config/kdesurc /home/$OUSER/.kde4/share/config/kdesurc ; do
			if [ -f "$i" ] ; then
				CHECK=$(cat "$i" | grep -aEi 'super-user-command')
				if [ "$CHECK" = "" ] ; then
					echo "" >> "$i"
					echo "[super-user-command]" >> "$i"
					echo "super-user-command=su" >> "$i"
					chown $(id -nu "$OUSER"):$(id -ng "$OUSER") "$i"
				else
					sed -i "s|command=sudo|command=su|g" "$i"
					chown $(id -nu "$OUSER"):$(id -ng "$OUSER") "$i"
				fi
				
				if [ "$SUDOCONFIG" = "Y" ] ; then
					sed -i 's|command=su|command=sudo|g' "$i"
					chown $(id -nu "$OUSER"):$(id -ng "$OUSER") "$i"
				fi
			fi
		done
	done
			
	for OUSER in $NEWUSERNAME $GUESTNAME ; do
		if [ -e /home/$OUSER/.gconf/apps/gksu/%gconf.xml ] ; then
			sed -i '/sudo-mode/ s|true|false|g' /home/$OUSER/.gconf/apps/gksu/%gconf.xml
			chown $(id -nu "$OUSER"):$(id -ng "$OUSER") /home/$OUSER/.gconf/apps/gksu/%gconf.xml
			
			if [ "$SUDOCONFIG" = "Y" ] ; then
				sed -i '/sudo-mode/ s|false|true|g' /home/$OUSER/.gconf/apps/gksu/%gconf.xml
				chown $(id -nu "$OUSER"):$(id -ng "$OUSER") /home/$OUSER/.gconf/apps/gksu/%gconf.xml
			fi
		fi
	done
	
	for OUSER in $NEWUSERNAME $GUESTNAME ; do
		if [ -e /home/$OUSER/.su-to-rootrc ] ; then
			sed -i 's|SU_TO_ROOT_SU=.*|SU_TO_ROOT_SU=su|g' /home/$OUSER/.su-to-rootrc
			sed -i 's|SU_TO_ROOT=sudo|SU_TO_ROOT=su|g' /home/$OUSER/.su-to-rootrc
			chown $(id -nu "$OUSER"):$(id -ng "$OUSER") /home/$OUSER/.su-to-rootrc
			
			if [ "$SUDOCONFIG" = "Y" ] ; then
				sed -i 's|SU_TO_ROOT_SU=su|SU_TO_ROOT_SU=sudo|g' /home/$OUSER/.su-to-rootrc
				sed -i 's|SU_TO_ROOT=su|SU_TO_ROOT=sudo|g' /home/$OUSER/.su-to-rootrc
				chown $(id -nu "$OUSER"):$(id -ng "$OUSER") /home/$OUSER/.su-to-rootrc
			fi
		fi
	done
	
#fi

# sudo disabling

if [ "$SUDOCONFIG" != "Y" ] ; then

	groupdel sudo
	groupdel wheel

	find /etc/ -type f | grep -a /etc/sudoers | while read i ; do sed -i "s|^.sudo|#&|g" "$i" ; done
	find /etc/ -type f | grep -a /etc/sudoers | while read i ; do sed -i "s|^.wheel|#&|g" "$i" ; done

else

	usermod -a -G sudo $NEWUSERNAME
	
	CHECKSUDO1=$(cat /etc/sudoers | grep -aE "^%sudo")
	if [ "$CHECKSUDO1" = "" ] ; then
		CHECKSUDO2=$(cat /etc/sudoers | grep -aE "^#%sudo")
		if [ "$CHECKSUDO2" = "" ] ; then
			echo "%sudo ALL=(ALL:ALL) ALL" >> /etc/sudoers
		else
			sed -i "s|^#%sudo|%sudo|g" /etc/sudoers
		fi
	fi

fi

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

shadowconfig on

# If change users is Yes
fi


### INTERNET TEST ########################################

ping -c 3 ftp.fau.de || ping -c 3 mirrorservice.org || ping -c 3 ftp.ch.debian.org

if [ "$?" -eq 0 ] ; then
	TESTINTERNET="Y"
else
	echo "No PING (no ICMP). Pass-through test..."
	wget http://ftp.fau.de -O /dev/null || wget http://mirrorservice.org -O /dev/null || wget http://ftp.ch.debian.org -O /dev/null
	if [ "$?" -eq 0 ] ; then
		echo "WGET (TCP connections) works. Internet OK."
		TESTINTERNET="Y"
	else
		echo $"No Internet connection."
		TESTINTERNET="N"
	fi
fi


### Set time using the Internet ########################################

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

	date --set "$(wget -qSO- --max-redirect=0 ftp.fau.de 2>&1 | sed -n 's|.*Date: ||p')" || date --set "$(wget -qSO- --max-redirect=0 mirrorservice.org 2>&1 | sed -n 's|.*Date: ||p')" || date --set "$(wget -qSO- --max-redirect=0 ftp.ch.debian.org 2>&1 | sed -n 's|.*Date: ||p')"
	if [ "$(command -v chronyc)" != "" ] ; then
		chronyc makestep
	elif [ "$(command -v ntpdate)" != "" ] ; then
		cat /etc/ntpsec/ntp.conf | grep -aEi ^server | awk '{print $2}' | while read i ; do
			ntpdate -b -u $i
			if [ "$?" -eq 0 ] ; then
				break
			fi
		done
	elif [ "$(command -v ntpdig)" != "" ] ; then
		cat /etc/ntpsec/ntp.conf | grep -aEi ^server | awk '{print $2}' | while read i ; do
			ntpdig -S $i
			if [ "$?" -eq 0 ] ; then
				break
			fi
		done
	elif [ "$(command -v sntp)" != "" ] ; then
		cat /etc/ntpsec/ntp.conf | grep -aEi ^server | awk '{print $2}' | while read i ; do
			sntp -S $i
			if [ "$?" -eq 0 ] ; then
				break
			fi
		done
	else
		echo "No NTP"
	fi

fi


### UPDATES ########################################

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

	$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"Do you want to install updates? \n\nIt is recommended.\n" $H $W
	if [ "$?" -eq 0 ] ; then
		apt-actualiza
	fi

fi


# postinst ########################################

if [ -e /etc/pica-postinst ] ; then rm /etc/pica-postinst ; fi
#if [ -e /etc/pica-postinstCOP ] ; then
#	rm /etc/pica-postinst ; mv -f /etc/pica-postinstCOP /etc/pica-postinst
#elif [ "$(cat /etc/pica-postinst | grep -aE "^CLEAN=" | sed 's|CLEAN=||g' | grep -aEi "N")" != "" ] ; then
#	sed -i "/^CLEAN=/ s|=N|=Y|g"  /etc/pica-postinst
#	sed -i "/^CLEAN=/ s|=\"N|=\"Y|g"  /etc/pica-postinst
#else
#	true
#fi


### END ########################################

$DIALOG $WICON $WTITLE "$TITLE" $INFO  $WTEXT $"$TITLE finished.\n\nThank you very much for using PicaLibre. Visit the website www.picalibre.org for more information.\n" $H $W

$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"Do you want to delete $TITLE ? \n\nIt is recommended.\n" $H $W
if [ "$?" -eq 0 ] ; then
	apt-get purge -y pica1
fi

echo $(date +%Y-%m-%d_%H:%M:%S) $"End" >> "$ERRORLOG"

clean

#if [ "$(cat /etc/passwd | grep -aE ^$(whoami): | cut -d ':' -f 3 )" -eq 0 ] ; then
if [ "$(id -u)" -eq 0 ] && [ "$DEBUG" = "Y" ] ; then
	RECERRORLOG="$ERRORLOG"
	for i in $(cat /etc/passwd | awk -F ':' '{print $3,$1}' | sort -n | grep -aEi "00[0-9] " | awk '{print $2}') ; do AUSER=$(users | sed 's| |\n|g' | grep -aE "^$i$" | head -n 1) ; if [ "$AUSER" != "" ] ; then
		HOMEERRORLOG=/home/$i/.${CNAME}.log
		RECERRORLOG="$RECERRORLOG $HOMEERRORLOG "
		cp -v --remove-destination $ERRORLOG $HOMEERRORLOG
		if [ "$(id -nu $i)" != "" ] ; then chown $(id -nu $i):$(id -ng $i) $HOMEERRORLOG ; else chown 1000:1000 $HOMEERRORLOG ; fi
		chmod 600 $HOMEERRORLOG ; if [ "$(stat -c %U $HOMEERRORLOG)" != "$i" ] ; then chmod 666 $HOMEERRORLOG ; fi
		break
	fi ; done
fi

exit 0
