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

# pica-grub
#
# Install GRUB.
#
# 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, dpkg, findutils, gawk | mawk | original-awk, grep, lsof, mount, os-prober, parted, procps, sed, sysvinit-utils (<<2.88dsf-59.3) | init-system-helpers, util-linux
# Recommends: arch-test, lxterminal | sakura | xfce4-terminal, menu, pica-skel, x11-xkb-utils
# Suggests: btrfs-progs, cryptsetup, dmsetup, efibootmgr, inetutils-ping | iputils-ping, lvm2, mdadm, qemu-user-static | qemu-user-binfmt, binfmt-support, symlinks, tcplay, wget


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

CNAME="pica-grub"
VERSION="1.3.1"
TITLE="Pica-GRUB"
ICON="/usr/share/icons/pica-grub.png"

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

# Translations
if [ "$LANG" = "" ] ; then export $(cat /etc/default/locale | grep -a 'LANG=') ; fi
TEXTDOMAIN=pica-grub
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=$"Install GRUB."
LDESCRIP=$"$TITLE is a tool to install the GRUB boot manager."

# 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

# Options:

# $DTMP
DTMP=/dtmp


### 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


### 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
}


### 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 ########################################

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

clean () {
if [ -e $DTMP/chroot.log ] ; then mv -f $DTMP/chroot.log $HOME/chroot.log ; fi
rm -f /lsvar /datarecscript /chrootscript /chroot.log $DTMP/lsvar $DTMP/datarecscript $DTMP/chrootscript $DTMP/chroot.log /dtmp/lsvar /dtmp/datarecscript /dtmp/chrootscript /dtmp/chroot.log /tmp/hostarc /tmp/guestarc /tmp/coincidarc $DTMP/update-grub-legacy $DTMP/grub-batch /dtmp/update-grub-legacy /dtmp/grub-batch
if [ "$DTMP" != "" ] ; then
	if [ "$(find $DTMP -type f)" = "" ] ; then find "$DTMP" -type d  | awk '{print length($1)"\t"$1}' | sort -n -r | cut -f 2 | while read i ; do rmdir "$i" ; done ; fi
	rmdir $DTMP
fi
unset OBJSYSPARTLIST PRE_OBJSYSPART OBJSYSPART RSYSPART RSYSPARTUUID GRUBVERSEL EFIGRUBVERSEL EFIPARTFSTAB EFIDET PREGRUBINSLOC SELGRUBINSLOC GRUBINSLOC
}

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 ########################################

#clean

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

$DIALOG $WICON $WTITLE "$TITLE" $INFO  $WTEXT $"Welcome to $TITLE.\n\n$TITLE is a tool to install the GRUB boot manager.\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


### CLOCK CHECK ########################################

YMD="$(date +%Y-%m-%d)"
if [ "$(date +%Y)" -lt 2025 ] ; then
	$DIALOG $WICON $WTITLE "$TITLE" $WM    $WTEXT $"The clock seems to be in the past: $YMD \nIf it is a computer with a button battery to keep time, then the button battery probably needs to be replaced (if this is not the first time this computer is turned on), to prevent the clock reverting to the past every time the computer loses power." $H $W
fi


### NOMODESET OPTION ########################################

NOMODESETCHECK=$(cat /proc/cmdline | grep -aEio nomodeset )
echo "NOMODESETCHECK=\"$NOMODESETCHECK\"" | tee -a /lsvar


### Activate or inactivate encrypted volumes ########################################

act_crypt () {

CRYPTACTIVEPARTS=$(lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' crypt' | awk '{print "/dev/"$1}' | sort -u | while read i ; do lsblk -r -n -o NAME,KNAME,TYPE -s $i | grep -aEiv ' disk' | awk '{print "/dev/"$2}' | grep -aEiv "^$i$" ; done | sort -u )
if [ "$CRYPTACTIVEPARTS" = "" ] ; then
	INACTIVECRYPTPARTS=$(lsblk -r -n -o KNAME,RM,FSTYPE | grep -aEi 'crypt' | awk '{print "/dev/"$1}' | sort -u | while read i ; do lsblk -r -n -o NAME,KNAME,TYPE -s $i | grep -aEiv ' disk' | awk '{print "/dev/"$2}' ; done | sort -u )
else
	INACTIVECRYPTPARTS=$(lsblk -r -n -o KNAME,RM,FSTYPE | grep -aEi 'crypt' | awk '{print "/dev/"$1}' | sort -u | while read i ; do lsblk -r -n -o NAME,KNAME,TYPE -s $i | grep -aEiv ' disk' | awk '{print "/dev/"$2}' ; done | sort -u | grep -av "$CRYPTACTIVEPARTS")
fi

if [ "$CRYPTACTIVEPARTS" != "" ] ; then
	INFOCRYPTACTIVEPARTS=$(echo $"Partitions that contain active encrypted volumes:" ; lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' crypt' | awk '{print "/dev/"$1}' | sort -u | while read i ; do echo "$i : $(lsblk -r -n -o NAME,KNAME,TYPE -s $i | grep -aEiv ' disk' | awk '{print "/dev/"$2}' | grep -aEiv "^$i$" | tr "\n" " ")" ; done | sort -u ; echo \\n )
else
	INFOCRYPTACTIVEPARTS=""
fi

if [ "$INACTIVECRYPTPARTS" != "" ] ; then
	INFOINACTIVEQCRYPT=$"The partitions\n$INACTIVECRYPTPARTS\ncontain inactive encrypted volumes.\n\n"
else
	INFOINACTIVEQCRYPT=""
fi

if [ "$CRYPTACTIVEPARTS" != "" ] || [ "$INACTIVECRYPTPARTS" != "" ] ; then

echo "### lsblk ##########"
lsblk -o NAME,KNAME,RM,SIZE,RO,TYPE,FSTYPE,MOUNTPOINT,LABEL,UUID
echo "### blkid ##########"
blkid
echo "### by-id ##########"
ls -l /dev/disk/by-id/
echo "#############"

	if [ "$(command -v cryptsetup)" != "" ] ; then
	QCRYPT=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"${INFOCRYPTACTIVEPARTS}${INFOINACTIVEQCRYPT}Please select an option:" $H $W $LH $COLUMN $COLUMN $"Activate all identified encrypted volumes" " " $"Inactivate all activated encrypted volumes" " " $"Leave as is" " " | head -n 1 )
	elif [ "$(command -v dmsetup)" != "" ] ; then
	QCRYPT=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"${INFOCRYPTACTIVEPARTS}${INFOINACTIVEQCRYPT}Please select an option:" $H $W $LH $COLUMN $COLUMN $"Inactivate all activated encrypted volumes" " " $"Leave as is" " " | head -n 1 )
	else
	true
	fi

	case $QCRYPT in
	
		$"Activate all identified encrypted volumes" )

# Open all existing encrypted volumes WITH headers:
#cat << EOF > /tmp/opencrypt
cat > /tmp/opencrypt <<EOF
#!/bin/bash

CNAME=$CNAME
VERSION=$VERSION
TITLE=$TITLE

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

ERRORLOG="$ERRORLOG"
if [ "$DEBUG" = "Y" ] ; then
	set -xv
fi
if [ "$DEBUG" != "N" ] ; then
exec > >(tee -a "\$ERRORLOG") 2>&1
echo "\$0" "\$*" >> "\$ERRORLOG"
fi

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

CRYPTACTIVEPARTS=\$(lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' crypt' | awk '{print "/dev/"\$1}' | sort -u | while read i ; do lsblk -r -n -o NAME,KNAME,TYPE -s \$i | grep -aEiv ' disk' | awk '{print "/dev/"\$2}' | grep -aEiv "^\$i\$" ; done | sort -u )

if [ "\$CRYPTACTIVEPARTS" = "" ] ; then
	for i in \$(lsblk -r -n -o KNAME,RM,FSTYPE | grep -aEi 'crypt' | awk '{print "/dev/"\$1}' | sort -u ) ; do lsblk -r -n -o KNAME,SIZE,LABEL,UUID | grep -aE "^\$(echo \$i | sed 's|/dev/||g') " ; cryptsetup luksOpen \$i e\$(echo \$i | sed 's|/dev/||g') ; done
else
	for i in \$(lsblk -r -n -o KNAME,RM,FSTYPE | grep -aEi 'crypt' | awk '{print "/dev/"\$1}' | sort -u | grep -av "\$CRYPTACTIVEPARTS" ) ; do lsblk -r -n -o KNAME,SIZE,LABEL,UUID | grep -aE "^\$(echo \$i | sed 's|/dev/||g') " ; cryptsetup luksOpen \$i e\$(echo \$i | sed 's|/dev/||g') ; done
fi

EOF

chmod +x /tmp/opencrypt

exec >/dev/tty
TT="$TITLE" ; COM="bash /tmp/opencrypt" ; TERMINAL ; rm -f /tmp/opencrypt
if [ "$DEBUG" != "N" ] ; then
	exec > >(tee -a "$ERRORLOG") 2>&1
fi

		;;
	
		$"Inactivate all activated encrypted volumes" )
		lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' crypt' | awk '{print "/dev/"$1}' | sort -u | while read i ; do
			echo "$i"
			umount $i
			cryptsetup luksClose $i
			tcplay -u $i
			dmsetup remove $i
			## umount /dev/dm*
			#dmsetup remove_all
		done
		;;
	
		*)
		echo "\$?=$?"
		echo QCRYPT=$QCRYPT
		;;

	esac

fi

symlinks -drs /dev/ >>$ERRORLOG
ls -p /dev/ | grep -a / | while read i ; do rmdir -p /dev/$i 2>>$ERRORLOG ; done

}

act_crypt


### Activate or inactivate LVM ########################################

act_lvm () {

LVMACTIVEPARTS=$(lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' lvm' | awk '{print "/dev/"$1}' | sort -u | while read i ; do lsblk -r -n -o NAME,KNAME,TYPE -s $i | grep -aEiv ' disk' | awk '{print "/dev/"$2}' | grep -aEiv "^$i$" ; done | sort -u )
if [ "$LVMACTIVEPARTS" = "" ] ; then
	INACTIVELVMPARTS=$(lsblk -r -n -o KNAME,RM,FSTYPE | grep -aEi 'lvm' | awk '{print "/dev/"$1}' | sort -u | while read i ; do lsblk -r -n -o NAME,KNAME,TYPE -s $i | grep -aEiv ' disk' | awk '{print "/dev/"$2}' ; done | sort -u )
else
	INACTIVELVMPARTS=$(lsblk -r -n -o KNAME,RM,FSTYPE | grep -aEi 'lvm' | awk '{print "/dev/"$1}' | sort -u | while read i ; do lsblk -r -n -o NAME,KNAME,TYPE -s $i | grep -aEiv ' disk' | awk '{print "/dev/"$2}' ; done | sort -u | grep -av "$LVMACTIVEPARTS")
fi

if [ "$LVMACTIVEPARTS" != "" ] ; then
#	INFOLVMACTIVEPARTS=$(echo $"Active 'LVM' extended volumes:" ; LANG=C pvscan | grep -aEiv 'Total: ' | grep -aEiv "No matching|No device" | awk '{if ( $4 !~ /\[/ ) print $4}' | sort -u | while read i ; do echo "$(echo $(lsblk -r -n -o NAME,KNAME | grep -aEi "^$i-" | grep -aEiv '_rmeta_|_rimage_' | awk '{print "/dev/"$NF}' | sort -u ))"" '""$i""' "$"formed by the partitions ""$(echo $(pvscan | grep -aE " $i " | awk '{print $2}' | sort -u | grep -av unknown | xargs -r0 readlink -m | grep -aEi "[a-zA-Z0-9]" ))" ; done ; echo \\n )
#	INFOLVMACTIVEPARTS=$(echo $"Active 'LVM' extended volumes:" ; LANG=C pvscan | grep -aEiv 'Total: ' | grep -aEiv "No matching|No device" | awk '{if ( $3 == "VG" ) print $4}' | sort -u | while read i ; do echo "$(echo $(lsblk -r -n -o NAME,KNAME | grep -aEi "^$i-" | grep -aEiv '_rmeta_|_rimage_' | awk '{print "/dev/"$NF}' | sort -u ))"" '""$i""' "$"formed by the partitions ""$(echo $(pvscan | grep -aE " $i " | awk '{print $2}' | sort -u | grep -av unknown | xargs -r0 readlink -m | grep -aEi "[a-zA-Z0-9]" ))" ; done ; echo \\n )
#	INFOLVMACTIVEPARTS=$(echo $"Active 'LVM' extended volumes:" ; lvs --noheadings --unbuffered -o vg_name,lv_name | sed 's|-|--|g' | sed "s|^ \+||g" | sed "s| \+$||g" | sed 's| |-|g' | sort -u | while read i ; do echo "$(echo $(lsblk -r -n -o NAME,KNAME | grep -aEi "^$i " | grep -aEiv '_rmeta_|_rimage_' | awk '{print "/dev/"$NF}' | sort -u ))"" '""$i""' "$"formed by the partitions ""$(echo $(pvscan | grep -aE " $(echo $i | grep -aEio ".*[a-zA-Z0-9]-[a-zA-Z0-9]" | sed "s|..$||g" | sed 's|--|-|g') " | awk '{print $2}' | sort -u | grep -av unknown | xargs -r0 readlink -m | grep -aEi "[a-zA-Z0-9]"))" ; done ; echo \\n )
	INFOLVMACTIVEPARTS=$(echo $"Active 'LVM' extended volumes:" ; lsblk -r -n -o NAME,KNAME,RM,TYPE | grep -aEi ' lvm' | awk '{if ( $4 == "lvm" ) print $1}' | grep -aEi "[a-zA-Z0-9]" | sort -u | while read i ; do echo "$(echo $(lsblk -r -n -o NAME,KNAME | grep -aEi "^$i " | grep -aEiv '_rmeta_|_rimage_' | awk '{print "/dev/"$NF}' | sort -u ))"" '""$i""' "$"formed by the partitions ""$(echo $(pvscan | grep -aE " $(echo $i | grep -aEio ".*[a-zA-Z0-9]-[a-zA-Z0-9]" | sed "s|..$||g" | sed 's|--|-|g') " | awk '{print $2}' | sort -u | grep -av unknown | xargs -r0 readlink -m | grep -aEi "[a-zA-Z0-9]" | grep -aEi "[a-zA-Z0-9]" | while read j ; do lsblk -r -n -o NAME,KNAME,TYPE -s $j | grep -aEiv ' disk' | awk '{print "/dev/"$2}' ; done | sort -u))" ; done ; echo \\n )
else
	INFOLVMACTIVEPARTS=""
fi

if [ "$INACTIVELVMPARTS" != "" ] ; then
	INFOINACTIVELVMPARTS=$"The partitions\n$INACTIVELVMPARTS\nare part of inactive 'LVM' extended volumes.\n\n"
else
	INFOINACTIVELVMPARTS=""
fi

if [ "$(command -v vgchange)" != "" ] ; then if [ "$LVMACTIVEPARTS" != "" ] || [ "$INACTIVELVMPARTS" != "" ] ; then

echo "### lsblk ##########"
lsblk -o NAME,KNAME,RM,SIZE,RO,TYPE,FSTYPE,MOUNTPOINT,LABEL,UUID
echo "### blkid ##########"
blkid
echo "### by-id ##########"
ls -l /dev/disk/by-id/
echo "#############"

	QLVM=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"${INFOLVMACTIVEPARTS}${INFOINACTIVELVMPARTS}Please select an option:" $H $W $LH $COLUMN $COLUMN $"Activate all 'LVM' extended volumes" " " $"Inactivate all 'LVM' extended volumes" " " $"Leave as is" " " | head -n 1 )

	case $QLVM in
	
		$"Activate all 'LVM' extended volumes" )
		vgchange -ay
		#pvscan --cache -aay
		;;
	
		$"Inactivate all 'LVM' extended volumes" )
		lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' lvm' | awk '{print "/dev/"$1}' | sort -u | while read i ; do umount $i ; done
		vgchange -an
		;;
	
		*)
		echo "\$?=$?"
		echo QLVM=$QLVM
		;;

	esac

fi ; fi

symlinks -drs /dev/ >>$ERRORLOG
ls -p /dev/ | grep -a / | while read i ; do rmdir -p /dev/$i 2>>$ERRORLOG ; done

}

act_lvm


### Activate or inactivate RAID ########################################

act_mdadm () {

MDADMACTIVEPARTS=$(lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' raid' | awk '{print "/dev/"$1}' | sort -u | while read i ; do mdadm --detail $i | grep -a " /dev/" | awk '{print $NF}' | sort -u | xargs -r0 readlink -m | grep -aEi "[a-zA-Z0-9]" | while read j ; do lsblk -r -n -o NAME,KNAME,TYPE -s $j | grep -aEiv ' disk' | awk '{print "/dev/"$2}' ; done ; done | grep -aEi "[a-zA-Z0-9]" | sort -u )
if [ "$MDADMACTIVEPARTS" = "" ] ; then
	INACTIVEMDADMPARTS=$(lsblk -r -n -o KNAME,RM,FSTYPE | grep -aEi 'raid' | awk '{print "/dev/"$1}' | sort -u | while read i ; do lsblk -r -n -o NAME,KNAME,TYPE -s $i | grep -aEiv ' disk' | awk '{print "/dev/"$2}' ; done | sort -u )
else
	INACTIVEMDADMPARTS=$(lsblk -r -n -o KNAME,RM,FSTYPE | grep -aEi 'raid' | awk '{print "/dev/"$1}' | sort -u | while read i ; do lsblk -r -n -o NAME,KNAME,TYPE -s $i | grep -aEiv ' disk' | awk '{print "/dev/"$2}' ; done | sort -u | grep -av "$MDADMACTIVEPARTS")
fi

if [ "$MDADMACTIVEPARTS" != "" ] ; then
	INFOMDADMACTIVEPARTS=$(echo $"Active 'mdadm' RAID partitions systems:" ; lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' raid' | awk '{print "/dev/"$1}' | sort -u | while read i ; do echo $i $"formed by the partitions" $(mdadm --detail $i | grep -a " /dev/" | awk '{print $NF}' | sort -u | xargs -r0 readlink -m | grep -aEi "[a-zA-Z0-9]" | while read j ; do lsblk -r -n -o NAME,KNAME,TYPE -s $j | grep -aEiv ' disk' | awk '{print "/dev/"$2}' ; done | sort -u) ; done ; echo \\n )
else
	INFOMDADMACTIVEPARTS=""
fi

if [ "$INACTIVEMDADMPARTS" != "" ] ; then
	INFOINACTIVEMDADMPARTS=$"The partitions\n$INACTIVEMDADMPARTS\nare part of inactive RAID partitions systems.\n\n"
else
	INFOINACTIVEMDADMPARTS=""
fi

if [ "$(command -v mdadm)" != "" ] ; then if [ "$MDADMACTIVEPARTS" != "" ] || [ "$INACTIVEMDADMPARTS" != "" ] ; then

echo "### lsblk ##########"
lsblk -o NAME,KNAME,RM,SIZE,RO,TYPE,FSTYPE,MOUNTPOINT,LABEL,UUID
echo "### blkid ##########"
blkid
echo "### by-id ##########"
ls -l /dev/disk/by-id/
echo "#############"

	QMDADM=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"${INFOMDADMACTIVEPARTS}${INFOINACTIVEMDADMPARTS}Please select an option:" $H $W $LH $COLUMN $COLUMN $"Activate all RAID partitions systems" " " $"Inactivate all RAID partitions systems" " " $"Leave as is" " " | head -n 1 )

	case $QMDADM in
	
		$"Activate all RAID partitions systems" )
		mdadm --assemble --scan
		;;
	
		$"Inactivate all RAID partitions systems" )
		lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' raid' | awk '{print "/dev/"$1}' | sort -u | while read i ; do umount $i ; done
		mdadm --stop --scan
		;;
	
		*)
		echo "\$?=$?"
		echo QMDADM=$QMDADM
		;;

	esac

fi ; fi

symlinks -drs /dev/ >>$ERRORLOG
ls -p /dev/ | grep -a / | while read i ; do rmdir -p /dev/$i 2>>$ERRORLOG ; done

}

act_mdadm


### Partitions ########################################

# lsblk - add inverse tree support (-s)  https://mirrors.kernel.org/pub/linux/utils/util-linux/v2.22/v2.22-ReleaseNotes	(Debian 8 "Jessie")

recparts () {

echo "### lsblk ##########"
lsblk -o NAME,KNAME,RM,SIZE,RO,TYPE,FSTYPE,MOUNTPOINT,LABEL,UUID
echo "### blkid ##########"
blkid
echo "### by-id ##########"
ls -l /dev/disk/by-id/
echo "#############"

CRYPTACTIVEPARTS=$(lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' crypt' | awk '{print "/dev/"$1}' | sort -u | while read i ; do lsblk -r -n -o NAME,KNAME,TYPE -s $i | grep -aEiv ' disk' | awk '{print "/dev/"$2}' | grep -aEiv "^$i$" ; done | sort -u )
LVMACTIVEPARTS=$(lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' lvm' | awk '{print "/dev/"$1}' | sort -u | while read i ; do lsblk -r -n -o NAME,KNAME,TYPE -s $i | grep -aEiv ' disk' | awk '{print "/dev/"$2}' | grep -aEiv "^$i$" ; done | sort -u )
btrfs device scan ; BTRFSRAIDACTIVEPARTS=$(LANG=C btrfs filesystem show | sed ':a;N;$!ba;s|\n\t| |g' | grep -aEi "[a-zA-Z0-9]" | grep -aEi 'Total devices ' | grep -aEiv 'Total devices 1 ' | while read i ; do echo $i | sed 's| |\n|g' | grep -aE "^/dev/" | sort -u | xargs -r0 readlink -m | grep -aEi "[a-zA-Z0-9]" | while read j ; do lsblk -r -n -o NAME,KNAME,TYPE -s $j | grep -aEiv ' disk' | awk '{print "/dev/"$2}' ; done | sed -n '2,$p' ; done | grep -aEi "[a-zA-Z0-9]" | sort -u )
MDADMACTIVEPARTS=$(lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' raid' | awk '{print "/dev/"$1}' | sort -u | while read i ; do mdadm --detail $i | grep -a " /dev/" | awk '{print $NF}' | sort -u | xargs -r0 readlink -m | grep -aEi "[a-zA-Z0-9]" | while read j ; do lsblk -r -n -o NAME,KNAME,TYPE -s $j | grep -aEiv ' disk' | awk '{print "/dev/"$2}' ; done ; done | grep -aEi "[a-zA-Z0-9]" | sort -u )

RECPARTS=$(echo "$CRYPTACTIVEPARTS $LVMACTIVEPARTS $BTRFSRAIDACTIVEPARTS $MDADMACTIVEPARTS" | sed 's| |\n|g' | grep -aE "[a-zA-Z0-9]" | grep -aE "[a-z]" | sort )

if [ "$CRYPTACTIVEPARTS" != "" ] ; then
INFOCRYPTACTIVEPARTS=$(echo $"Partitions that contain active encrypted volumes:" ; lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' crypt' | awk '{print "/dev/"$1}' | sort -u | while read i ; do echo "$i : $(lsblk -r -n -o NAME,KNAME,TYPE -s $i | grep -aEiv ' disk' | awk '{print "/dev/"$2}' | grep -aEiv "^$i$" | tr "\n" " ")" ; done | sort -u ; echo \\n )
else
INFOCRYPTACTIVEPARTS=""
fi

if [ "$LVMACTIVEPARTS" != "" ] ; then
#INFOLVMACTIVEPARTS=$(echo $"Active 'LVM' extended volumes:" ; LANG=C pvscan | grep -aEiv 'Total: ' | grep -aEiv "No matching|No device" | awk '{if ( $4 !~ /\[/ ) print $4}' | sort -u | while read i ; do echo "$(echo $(lsblk -r -n -o NAME,KNAME | grep -aEi "^$i-" | grep -aEiv '_rmeta_|_rimage_' | awk '{print "/dev/"$NF}' | sort -u ))"" '""$i""' "$"formed by the partitions ""$(echo $(pvscan | grep -aE " $i " | awk '{print $2}' | sort -u | grep -av unknown | xargs -r0 readlink -m | grep -aEi "[a-zA-Z0-9]" ))" ; done ; echo \\n )
#INFOLVMACTIVEPARTS=$(echo $"Active 'LVM' extended volumes:" ; LANG=C pvscan | grep -aEiv 'Total: ' | grep -aEiv "No matching|No device" | awk '{if ( $3 == "VG" ) print $4}' | sort -u | while read i ; do echo "$(echo $(lsblk -r -n -o NAME,KNAME | grep -aEi "^$i-" | grep -aEiv '_rmeta_|_rimage_' | awk '{print "/dev/"$NF}' | sort -u ))"" '""$i""' "$"formed by the partitions ""$(echo $(pvscan | grep -aE " $i " | awk '{print $2}' | sort -u | grep -av unknown | xargs -r0 readlink -m | grep -aEi "[a-zA-Z0-9]" ))" ; done ; echo \\n )
#INFOLVMACTIVEPARTS=$(echo $"Active 'LVM' extended volumes:" ; lvs --noheadings --unbuffered -o vg_name,lv_name | sed 's|-|--|g' | sed "s|^ \+||g" | sed "s| \+$||g" | sed 's| |-|g' | sort -u | while read i ; do echo "$(echo $(lsblk -r -n -o NAME,KNAME | grep -aEi "^$i " | grep -aEiv '_rmeta_|_rimage_' | awk '{print "/dev/"$NF}' | sort -u ))"" '""$i""' "$"formed by the partitions ""$(echo $(pvscan | grep -aE " $(echo $i | grep -aEio ".*[a-zA-Z0-9]-[a-zA-Z0-9]" | sed "s|..$||g" | sed 's|--|-|g') " | awk '{print $2}' | sort -u | grep -av unknown | xargs -r0 readlink -m | grep -aEi "[a-zA-Z0-9]"))" ; done ; echo \\n )
INFOLVMACTIVEPARTS=$(echo $"Active 'LVM' extended volumes:" ; lsblk -r -n -o NAME,KNAME,RM,TYPE | grep -aEi ' lvm' | awk '{if ( $4 == "lvm" ) print $1}' | grep -aEi "[a-zA-Z0-9]" | sort -u | while read i ; do echo "$(echo $(lsblk -r -n -o NAME,KNAME | grep -aEi "^$i " | grep -aEiv '_rmeta_|_rimage_' | awk '{print "/dev/"$NF}' | sort -u ))"" '""$i""' "$"formed by the partitions ""$(echo $(pvscan | grep -aE " $(echo $i | grep -aEio ".*[a-zA-Z0-9]-[a-zA-Z0-9]" | sed "s|..$||g" | sed 's|--|-|g') " | awk '{print $2}' | sort -u | grep -av unknown | xargs -r0 readlink -m | grep -aEi "[a-zA-Z0-9]" | grep -aEi "[a-zA-Z0-9]" | while read j ; do lsblk -r -n -o NAME,KNAME,TYPE -s $j | grep -aEiv ' disk' | awk '{print "/dev/"$2}' ; done | sort -u))" ; done ; echo \\n )
else
INFOLVMACTIVEPARTS=""
fi

if [ "$BTRFSRAIDACTIVEPARTS" != "" ] ; then
btrfs device scan ; INFOBTRFSACTIVEPARTS=$(echo $"Partitions that are part of 'btrfs' RAID partitions systems:" ; LANG=C btrfs filesystem show | sed ':a;N;$!ba;s|\n\t| |g' | grep -aEi "[a-zA-Z0-9]" | grep -aEi 'Total devices ' | grep -aEiv 'Total devices 1 ' | while read i ; do echo $(echo $i | sed 's| |\n|g' | grep -aE "^/dev/" | sort -u | xargs -r0 readlink -m | grep -aEi "[a-zA-Z0-9]" | while read j ; do lsblk -r -n -o NAME,KNAME,TYPE -s $j | grep -aEiv ' disk' | awk '{print "/dev/"$2}' ; done) ; done | grep -aEi "[a-zA-Z0-9]" | sort -u ; echo \\n )
else
INFOBTRFSACTIVEPARTS=""
fi

if [ "$MDADMACTIVEPARTS" != "" ] ; then
INFOMDADMACTIVEPARTS=$(echo $"Active 'mdadm' RAID partitions systems:" ; lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' raid' | awk '{print "/dev/"$1}' | sort -u | while read i ; do echo $i $"formed by the partitions" $(mdadm --detail $i | grep -a " /dev/" | awk '{print $NF}' | sort -u | xargs -r0 readlink -m | grep -aEi "[a-zA-Z0-9]" | while read j ; do lsblk -r -n -o NAME,KNAME,TYPE -s $j | grep -aEiv ' disk' | awk '{print "/dev/"$2}' ; done | sort -u) ; done ; echo \\n )
else
INFOMDADMACTIVEPARTS=""
fi

}

set_grubpart () {

recparts

if [ "$RECPARTS" = "" ] ; then
	OBJSYSPARTLIST=$(lsblk -r -n -o KNAME,RM,TYPE,NAME | grep -aEi ' part| crypt| raid| md| lvm| dm' | grep -aEiv '_rmeta_|_rimage_' | awk '{print "/dev/"$1}' | sort -u )
	OBJSYSPARTLISTSIZE=$(lsblk -r -n -o KNAME,RM,SIZE,TYPE,NAME | grep -aEi ' part| crypt| raid| md| lvm| dm' | grep -aEiv '_rmeta_|_rimage_' | awk '{print "/dev/"$1"\t"$3}' | sort -u )
	# label is optional and may contain spaces
	OBJSYSPARTLISTEXTRAINFO=$(lsblk -r -n -o KNAME,TYPE,SIZE,LABEL,NAME,UUID | grep -aEi ' part| crypt| raid| md| lvm| dm' | grep -aEiv '_rmeta_|_rimage_' | sort -u | while read i ; do printf "/dev/""$i""\n" | grep -aE "[0-9] " | sed 's| |     |1' ; done )
else
	OBJSYSPARTLIST=$(lsblk -r -n -o KNAME,RM,TYPE,NAME | grep -aEi ' part| crypt| raid| md| lvm| dm' | grep -aEiv '_rmeta_|_rimage_' | awk '{print "/dev/"$1}' | sort -u | grep -aEv "$(echo "$RECPARTS" | tr "\n" " " | tr " " "|" | sed 's:|:[^a-zA-Z0-9/-]|:g' | sed 's:|$::g')" )
	OBJSYSPARTLISTSIZE=$(lsblk -r -n -o KNAME,RM,SIZE,TYPE,NAME | grep -aEi ' part| crypt| raid| md| lvm| dm' | grep -aEiv '_rmeta_|_rimage_' | awk '{print "/dev/"$1"\t"$3}' | sort -u | grep -aEv "$(echo "$RECPARTS" | tr "\n" " " | tr " " "|" | sed 's:|:[^a-zA-Z0-9/-]|:g' | sed 's:|$::g')" )
	# label is optional and may contain spaces
	OBJSYSPARTLISTEXTRAINFO=$(lsblk -r -n -o KNAME,TYPE,SIZE,LABEL,NAME,UUID | grep -aEi ' part| crypt| raid| md| lvm| dm' | grep -aEiv '_rmeta_|_rimage_' | sort -u | while read i ; do printf "/dev/""$i""\n" | grep -aEv "$(echo "$RECPARTS" | tr "\n" " " | tr " " "|" | sed 's:|:[^a-zA-Z0-9/-]|:g' | sed 's:|$::g')" | grep -aE "[0-9] " | sed 's| |     |1' ; done )
fi

if [ "$(echo "$OBJSYSPARTLISTEXTRAINFO" | grep -a -c ^)" -gt 10 ] ; then
	OBJSYSPARTLISTEXTRAINFO=""
fi

#OBJSYSPART=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"Please select the partition of the main operating system. ($TITLE will fail if the main operating system does not use '.deb' as package system).\n\nAvailable devices:\n$OBJSYSPARTLISTEXTRAINFO\n\nIf you don't know which one is, use a file manager (thunar, pcmanfm, konqueror, dolphin, caja,...) or a partition manager (gparted,...) to search it.\n\n(1 GB = 1000 MB; 1 GiB = 1024 MiB)\n\n${INFOCRYPTACTIVEPARTS}${INFOLVMACTIVEPARTS}${INFOBTRFSACTIVEPARTS}${INFOMDADMACTIVEPARTS}" $H $W $LH $COLUMN $COLUMN $OBJSYSPARTLISTSIZE | head -n 1 )

OBJSYSPART=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"Please select the partition of the main operating system. ($TITLE will fail if the main operating system does not use '.deb' as package system).\n\nAvailable devices:\n$OBJSYSPARTLISTEXTRAINFO\n\nIf you don't know which one is, use a file manager (thunar, pcmanfm, konqueror, dolphin, caja,...) or a partition manager (gparted,...) to search it.\n\n(1 GB = 1000 MB; 1 GiB = 1024 MiB)" $H $W $LH $COLUMN $COLUMN $OBJSYSPARTLISTSIZE | head -n 1 )

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

if [ "$OBJSYSPART" != "" ] ; then
	echo "OBJSYSPART=\"$OBJSYSPART\"" | tee -a /lsvar
	OBJSYSPARTUUID=$(lsblk -r -n -o UUID $OBJSYSPART | head -n 1 )
	if [ "$OBJSYSPARTUUID" = "" ] ; then OBJSYSPARTUUID=$(blkid -o value -s UUID $OBJSYSPART | head -n 1 | sed 's|/dev/disk/by-uuid/||g') ; fi
	if [ "$OBJSYSPARTUUID" = "" ] ; then OBJSYSPARTUUID=$(find -L /dev/disk/by-uuid/ -samefile $OBJSYSPART | head -n 1 | sed 's|/dev/disk/by-uuid/||g') ; fi
	echo "OBJSYSPARTUUID=$OBJSYSPARTUUID" | tee -a /lsvar
	OBJSYSPARTID=$(find -L /dev/disk/by-id/ -samefile $OBJSYSPART | sort | tail -n 1 )
	echo "OBJSYSPARTID=$OBJSYSPARTID" | tee -a /lsvar
fi

}

set_grubpart


### CHECK CHROOT ########################################

RSYSPART=$(lsblk -r -n -o KNAME,MOUNTPOINT,UUID | grep -a ' / ' | awk '{print "/dev/"$1}' )
if [ "$RSYSPART" != "" ] ; then
	RSYSPARTUUID=$(lsblk -r -n -o UUID $RSYSPART | head -n 1 )
	if [ "$RSYSPARTUUID" = "" ] ; then RSYSPARTUUID=$(blkid -o value -s UUID $RSYSPART | head -n 1 | sed 's|/dev/disk/by-uuid/||g') ; fi
	if [ "$RSYSPARTUUID" = "" ] ; then RSYSPARTUUID=$(find -L /dev/disk/by-uuid/ -samefile $RSYSPART | head -n 1 | sed 's|/dev/disk/by-uuid/||g') ; fi
fi

if [ "$OBJSYSPART" = "$RSYSPART" ] && [ "$OBJSYSPARTUUID" = "$RSYSPARTUUID" ] ; then
	CHROOT="N"
	echo "CHROOT=\"N\"" | tee -a /lsvar
elif [ "$OBJSYSPART" = "$RSYSPART" ] || [ "$OBJSYSPARTUUID" = "$RSYSPARTUUID" ] ; then
	check_exit
else
	CHROOT="Y"
	echo "CHROOT=\"Y\"" | tee -a /lsvar
fi


# architecture of the host:

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

if [ "$(cat /tmp/hostarc | grep -aE "[a-zA-Z0-9]")" = "" ] ; then
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'amd64|x86_64|x86-64' )" != "" ] ; then echo " amd64 " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'armel|iop32x|ixp4xx|kirkwood|marvell|mv78xx0|orion5x|rpi|versatile|arm' )" != "" ] ; then echo " armel " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'armhf|armmp|mx5|omap|vexpress|armv' )" != "" ] ; then echo " armhf " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'arm64|aarch64' )" != "" ] ; then echo " arm64 " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi '386|486|586|686|x86_32|x86-32' )" != "" ] ; then echo " i386 " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'itanium|mckinley|ia64' )" != "" ] ; then echo " ia64 " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'loong64|loongarch64' )" != "" ] ; then echo " loong64 " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'bcm91|ip22|ip32|malta|mips|octeon' )" != "" ] ; then echo " mips " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'loongson|malta|mips64|octeon' )" != "" ] ; then echo " mips64el " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'loongson|bcm91|cobalt|malta|mips32|mipsel|octeon' )" != "" ] ; then echo " mipsel " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'powerpc|powerpc64|ppc|ppc64' )" != "" ] ; then echo " powerpc " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'powerpc64le|ppc64el|ppc64le' )" != "" ] ; then echo " ppc64el " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'riscv64|rv64' )" != "" ] ; then echo " riscv64 " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 's390x' )" != "" ] ; then echo " s390x " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'sparc' )" != "" ] ; then echo " sparc " >> /tmp/hostarc ; fi
	if [ "$(cat /boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'sparc64' )" != "" ] ; then echo " sparc64 " >> /tmp/hostarc ; fi
fi

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

sed -i "/^$/d" /tmp/hostarc

if [ "$(cat /tmp/hostarc)" != "" ] ; then
	cat /tmp/hostarc
else
	ls /boot/
	check_exit
fi


### PREPARE CHROOT ########################################

prep_chroot () {

# make mountpoint and mount it

if [ "$DTMP" = "" ] ; then
	check_exit
fi

mkdir -pv $DTMP
umount $OBJSYSPART
mount -o rw $OBJSYSPART $DTMP

if [ "$OBJSYSPARTID" != "" ] ; then
	if [ "$OBJSYSPARTUUID" != "" ] ; then
		if [ "$(cat /etc/mtab | grep -aEi "^$OBJSYSPART |^$OBJSYSPARTID |^/dev/disk/by-uuid/$OBJSYSPARTUUID |^UUID=$OBJSYSPARTUUID " | awk '{print $4}' | sed 's|,|\n|g' | grep -aEi "^ro$")" != "" ] ; then
			mount -o remount,rw "$OBJSYSPART" "$DTMP"
		fi
	else
		if [ "$(cat /etc/mtab | grep -aEi "^$OBJSYSPART |^$OBJSYSPARTID " | awk '{print $4}' | sed 's|,|\n|g' | grep -aEi "^ro$")" != "" ] ; then
			mount -o remount,rw "$OBJSYSPART" "$DTMP"
		fi
	fi
else
	if [ "$OBJSYSPARTUUID" != "" ] ; then
		if [ "$(cat /etc/mtab | grep -aEi "^$OBJSYSPART |^/dev/disk/by-uuid/$OBJSYSPARTUUID |^UUID=$OBJSYSPARTUUID " | awk '{print $4}' | sed 's|,|\n|g' | grep -aEi "^ro$")" != "" ] ; then
			mount -o remount,rw "$OBJSYSPART" "$DTMP"
		fi
	else
		if [ "$(cat /etc/mtab | grep -aEi "^$OBJSYSPART " | awk '{print $4}' | sed 's|,|\n|g' | grep -aEi "^ro$")" != "" ] ; then
			mount -o remount,rw "$OBJSYSPART" "$DTMP"
		fi
	fi
fi


# mount additional partitions (as /boot) if they are separated. Externally only if absolute (UUID) names are used.
cat $DTMP/etc/fstab | grep -aEiv "^#" | grep -aEiv ' /media/| / ' | grep -aEi "^UUID=" | while read i ; do
	umount /dev/disk/by-uuid/$(echo "$i" | awk '{print $1}' | sed 's|UUID=||g')
	mount -o rw $(echo "$i" | awk '{print $1}') ${DTMP}$(echo "$i" | awk '{print $2}')
done


# architecture of the guest:

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

if [ "$(cat /tmp/guestarc | grep -aE "[a-zA-Z0-9]")" = "" ] ; then
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'amd64|x86_64|x86-64' )" != "" ] ; then echo " amd64 " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'armel|iop32x|ixp4xx|kirkwood|marvell|mv78xx0|orion5x|rpi|versatile|arm' )" != "" ] ; then echo " armel " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'armhf|armmp|mx5|omap|vexpress|armv' )" != "" ] ; then echo " armhf " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'arm64|aarch64' )" != "" ] ; then echo " arm64 " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi '386|486|586|686|x86_32|x86-32' )" != "" ] ; then echo " i386 " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'itanium|mckinley|ia64' )" != "" ] ; then echo " ia64 " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'loong64|loongarch64' )" != "" ] ; then echo " loong64 " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'bcm91|ip22|ip32|malta|mips|octeon' )" != "" ] ; then echo " mips " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'loongson|malta|mips64|octeon' )" != "" ] ; then echo " mips64el " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'loongson|bcm91|cobalt|malta|mips32|mipsel|octeon' )" != "" ] ; then echo " mipsel " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'powerpc|powerpc64|ppc|ppc64' )" != "" ] ; then echo " powerpc " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'powerpc64le|ppc64el|ppc64le' )" != "" ] ; then echo " ppc64el " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'riscv64|rv64' )" != "" ] ; then echo " riscv64 " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 's390x' )" != "" ] ; then echo " s390x " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'sparc' )" != "" ] ; then echo " sparc " >> /tmp/guestarc ; fi
	if [ "$(cat $DTMP/boot/config-* | grep -ai CONFIG_OUTPUT_FORMAT | sort -u | grep -aEi 'sparc64' )" != "" ] ; then echo " sparc64 " >> /tmp/guestarc ; fi
fi

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

sed -i "/^$/d" /tmp/guestarc

if [ "$(cat /tmp/guestarc)" != "" ] ; then
	cat /tmp/guestarc
else
	ls $DTMP/boot/
	check_exit
fi


# check architectures host vs. guest

cat /tmp/hostarc | while read i ; do TEST=$(cat /tmp/guestarc | grep -a $i ) ; if [ "$TEST" != "" ] ; then echo " $i " >> /tmp/coincidarc ; fi ; done
cat /tmp/coincidarc
TESTCHROOTNATIV=$(cat /tmp/coincidarc | grep -aE "[a-zA-Z0-9]")
if [ "$TESTCHROOTNATIV" != "" ] ; then
	CHROOTNATIV="Y"
else
	CHROOTNATIV="N"
fi

if [ "$CHROOTNATIV" = "N" ] ; then
	TESTQEMU=$(dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2}' | sed "s|:.*||g" | grep -aEi "^qemu-user-static$|^qemu-user-binfmt$")
	if [ "$TESTQEMU" = "" ] ; then
		$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"You need to install install qemu-user-static or qemu-user-binfmt, and binfmt-support, before using $TITLE." $H $W
		exit 1
	fi
fi


### MOUNT FOR CHROOT ########################################

# mount for chroot
mount --rbind /dev/ $DTMP/dev/
#mount --bind /dev/pts/ $DTMP/dev/pts/
mount --rbind /proc/ $DTMP/proc/
mount --rbind /sys/ $DTMP/sys/
mount --rbind /run/ $DTMP/run/

}

UNAMER=$(echo "$(uname -mr) --- $(uname -a)")

# 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

if [ "$SYSARC" = "" ] ; then
	$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"ERROR: Processor type not identified ( $UNAMER ).\n\nCannot continue." $H $W
	check_exit
fi


if [ "$CHROOT" = "Y" ] ; then
	prep_chroot
	if   [ "$CHROOTNATIV" = "Y" ] ; then
		if [ "$(cat /tmp/coincidarc | grep -a $SYSARC )" = "" ] ; then
			SYSARC=$(cat /tmp/coincidarc | grep -aE "[a-zA-Z0-9]" | awk '{print length($1)"\t"$1}' | sort -n | cut -f 2 | tail -n 1 )
		fi
	elif [ "$CHROOTNATIV" = "N" ] ; then
		SYSARC=$(cat /tmp/guestarc | grep -aE "[a-zA-Z0-9]" | awk '{print length($1)"\t"$1}' | sort -n | cut -f 2 | tail -n 1 )
	else
		check_exit
	fi
	echo "SYSARC=\"$SYSARC\"" | tee -a /lsvar
	rm -f $DTMP/lsvar
	mv /lsvar $DTMP/lsvar
elif [ "$CHROOT" = "N" ] ; then
	echo "SYSARC=\"$SYSARC\"" | tee -a /lsvar
	DTMP=""
else
	check_exit
fi


### QEMUARC ########################################

qemuarc () {

if   [ "$SYSARC" = "amd64"    ] ; then QEMUARC="x86_64"
elif [ "$SYSARC" = "armel"    ] ; then QEMUARC="arm"
elif [ "$SYSARC" = "armhf"    ] ; then QEMUARC="arm"
elif [ "$SYSARC" = "arm64"    ] ; then QEMUARC="aarch64"
elif [ "$SYSARC" = "i386"     ] ; then QEMUARC="i386"
elif [ "$SYSARC" = "ia64"     ] ; then QEMUARC="ia64"
elif [ "$SYSARC" = "mips"     ] ; then QEMUARC="mips"
elif [ "$SYSARC" = "mips64el" ] ; then QEMUARC="mips64el"
elif [ "$SYSARC" = "mipsel"   ] ; then QEMUARC="mipsel"
elif [ "$SYSARC" = "powerpc"  ] ; then QEMUARC="ppc"
elif [ "$SYSARC" = "ppc64"    ] ; then QEMUARC="ppc64"
elif [ "$SYSARC" = "ppc64el"  ] ; then QEMUARC="ppc64le"
elif [ "$SYSARC" = "sparc"    ] ; then QEMUARC="sparc"
elif [ "$SYSARC" = "sparc64"  ] ; then QEMUARC="sparc64"
elif [ "$SYSARC" = "alpha"    ] ; then QEMUARC="alpha"
elif [ "$SYSARC" = "hppa"     ] ; then QEMUARC="hppa"
elif [ "$SYSARC" = "loong64"  ] ; then QEMUARC="loongarch64"
elif [ "$SYSARC" = "m68k"     ] ; then QEMUARC="m68k"
elif [ "$SYSARC" = "or1k"     ] ; then QEMUARC="or1k"
elif [ "$SYSARC" = "riscv32"  ] ; then QEMUARC="riscv32"
elif [ "$SYSARC" = "riscv64"  ] ; then QEMUARC="riscv64"
elif [ "$SYSARC" = "s390x"    ] ; then QEMUARC="s390x"
elif [ "$SYSARC" = "sh4"      ] ; then QEMUARC="sh4"
else
	echo "ERROR: SYSARC = $SYSARC "
	check_exit
fi

# ls -l /usr/bin/ | grep -aEi "qemu-.*-static" | grep -aEi "\->" | tr -s " " | cut -d ' ' -f 9-
#qemu-amd64-static -> qemu-x86_64-static
#qemu-arm64-static -> qemu-aarch64-static
#qemu-armel-static -> qemu-arm-static
#qemu-armhf-static -> qemu-arm-static
#qemu-loong64-static -> qemu-loongarch64-static
#qemu-powerpc-static -> qemu-ppc-static
#qemu-ppc64el-static -> qemu-ppc64le-static

}


### DATARECSCRIPT ########################################

#cat << EOF > $DTMP/datarecscript
cat > $DTMP/datarecscript <<EOF
#!/bin/bash

CNAME=$CNAME
VERSION=$VERSION
TITLE=$TITLE

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

ERRORLOG="/chroot.log"
if [ -e "\$ERRORLOG" ] ; then
	mv -f \$ERRORLOG \${ERRORLOG}.ant
fi
if [ -e "\$ERRORLOG" ] ; then rm -rf "\$ERRORLOG" ; fi

if [ "$DEBUG" = "Y" ] ; then
	set -xv
fi
if [ "$DEBUG" != "N" ] ; then
exec > >(tee -a "\$ERRORLOG") 2>&1
echo "\$0" "\$*" >> "\$ERRORLOG"
echo "env:" >> "\$ERRORLOG"
env >> "\$ERRORLOG"
echo "set:" >> "\$ERRORLOG"
set >> "\$ERRORLOG"
fi

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

# rm chrootscript
rm -f chrootscript /chrootscript

# partitions

#udevadm control --reload-rules && udevadm trigger -v
mount -a

echo "Partition list:"
echo "### lsblk ##########"
lsblk -o NAME,KNAME,RM,SIZE,RO,TYPE,FSTYPE,MOUNTPOINT,LABEL,UUID
echo "### blkid ##########"
blkid
echo "### by-id ##########"
ls -l /dev/disk/by-id/
echo "#############"

echo "fstab:"
cat /etc/fstab

EFIPARTFSTAB=\$(echo \$(cat /etc/fstab | grep -aEiv "^#" | tr "\t" " " | grep -aEi ' /boot' | grep -aEi ' vfat ' | awk '{print \$2}' ) )

echo "EFIPARTFSTAB=\"\$EFIPARTFSTAB\"" | tee -a /lsvar

# GPT check:

	# Check if partition table is GPT
	DLIST=\$(lsblk -r -n -o KNAME,RM,TYPE | grep -aEi " 0 " | grep -aEi ' disk' | awk '{print "/dev/"\$1}' )
	if [ "\$DLIST" = "" ] ; then DLIST=\$(lsblk -r -n -o KNAME,RM,TYPE \$(echo \$(ls -l /dev/disk/by-id/ | grep -aEi ' ata| ide| pata| sata| scsi| sas| nvme| pci' | sed "s|.*/|/dev/|g")) | grep -aEi ' disk' | awk '{print "/dev/"\$1}') ; fi  # In some computers the internal disk can be wrongly shown as removable.
	if [ "\$DLIST" = "" ] ; then DLIST=\$(lsblk -r -n -o KNAME,RM,TYPE \$(echo \$(ls -l /dev/disk/by-id/ | sed "s|.*/|/dev/|g")) | grep -aEi ' disk' | awk '{print "/dev/"\$1}') ; fi  # In some computers the internal disk can be wrongly shown as removable.
	for i in \$DLIST ; do
		DTT=\$(LANG=C parted -s "\$i" print | grep -aEi 'Partition Tab' | awk '{print \$NF}')
#		if [ "\$DTT" != "msdos" ] ; then
		if [ "\$DTT" = "gpt" ] ; then
		GPTDET="\$i"
		echo "GPTDET=\"\$GPTDET\"" | tee -a /lsvar
		break
		fi
	done

# check guest GRUB version
echo guest GRUB version
GRUBVERIN=\$(echo \$(dpkg -l | grep -aEi "^ii|^hi" | awk '{print \$2}' | grep -aEi "^grub" | sed "s|:.*||g" | grep -aEiv "^grub2\$|\-choose\-|\-common\$|\-customizer\$|\-bin\$|\-dbg\$|\-dbgsym\$|\-disk\$|\-doc\$|\-efi\$|\-emu\$|\-firmware\-|\-grubby\$|\-image|\-installer\$|\-invaders\$|\-linuxbios\$|grub\-menu\$|\-mount\-|\-theme\-|\-rescue\-|\-splash|\-template" ) )
# grub2, grub-efi and grub-linuxbios are dummy transitional packages
echo "GRUBVERIN=\"\$GRUBVERIN\"" | tee -a /lsvar

# guest OS version
echo guest OS version
if [ "\$(command -v lsb_release)" != "" ] ; then lsb_release -a ; fi
if [ -e /etc/picalibre_version ] ; then echo /etc/picalibre_version ; cat /etc/picalibre_version ; fi
if [ -e /etc/debian_version ] ; then echo /etc/debian_version ; cat /etc/debian_version ; fi
if [ -e /etc/devuan_version ] ; then echo /etc/devuan_version ; cat /etc/devuan_version ; fi

EOF

chmod +x $DTMP/datarecscript

if [ "$CHROOT" = "Y" ] ; then
	if [ "$CHROOTNATIV" = "Y" ] ; then
		TT="$TITLE" ; COM="chroot $DTMP $(command -v bash) /datarecscript" ; TERMINAL
	elif [ "$CHROOTNATIV" = "N" ] ; then
		#chroot: failed to run command ‘/bin/bash’: Exec format error
		#update-binfmts --importdir /var/lib/binfmts/ --import
		qemuarc
		if [ "$(command -v qemu-${QEMUARC}-static)" = "" ] ; then
			$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"You need to install install qemu-user-static or qemu-user-binfmt, and binfmt-support, before using $TITLE." $H $W
			exit 1
		fi
		if [ ! -e "${DTMP}$(command -v qemu-${QEMUARC}-static)" ] ; then
			cp -v $(command -v qemu-${QEMUARC}-static) ${DTMP}$(command -v qemu-${QEMUARC}-static)
		else
			QEMUDEL="N"
		fi
		TT="$TITLE" ; COM="chroot $DTMP qemu-${QEMUARC}-static $(command -v bash) /datarecscript" ; TERMINAL
	else
		check_exit
	fi
else
	TT="$TITLE" ; COM="bash /datarecscript" ; TERMINAL
fi


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

cat $DTMP/lsvar

source $DTMP/lsvar

if [ "$EFIPARTFSTAB" != "" ] || [ -e /sys/firmware/efi ] ; then
	find /sys/firmware/efi
	EFIDET="Y"
fi

# check host GRUB version
echo host GRUB version
GRUBVERH=$(echo $(dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2}' | grep -aEi "^grub" | sed "s|:.*||g" | grep -aEiv "^grub2$|\-choose\-|\-common$|\-customizer$|\-bin$|\-dbg$|\-dbgsym$|\-disk$|\-doc$|\-efi$|\-emu$|\-firmware\-|\-grubby$|\-image|\-installer$|\-invaders$|\-linuxbios$|grub\-menu$|\-mount\-|\-theme\-|\-rescue\-|\-splash|\-template" ) | sed 's|grub-efi-amd64 grub-efi-amd64-signed|grub-efi-amd64|g' | sed 's|grub-efi-arm64 grub-efi-arm64-signed|grub-efi-arm64|g'| sed 's|grub-efi-ia32 grub-efi-ia32-signed|grub-efi-ia32|g')
# grub2, grub-efi and grub-linuxbios are dummy transitional packages
echo "GRUBVERH=\"$GRUBVERH\"" | tee -a $DTMP/lsvar

# host OS version
echo host OS version
if [ "$(command -v lsb_release)" != "" ] ; then lsb_release -a ; fi
if [ -e /etc/picalibre_version ] ; then cat /etc/picalibre_version >> "$ERRORLOG" ; PRE_PICAVERSION=$(cat /etc/picalibre_version | cut -d '.' -f 1 ) ; fi
if [ -e /etc/debian_version ] ; then cat /etc/debian_version >> "$ERRORLOG" ; PRE_DEBIANVERSION=$(cat /etc/debian_version | cut -d '.' -f 1 ) ; fi
if [ -e /etc/devuan_version ] ; then cat /etc/devuan_version >> "$ERRORLOG" ; 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 )

# GRUB options in function to the architecture
unset GRUBVERLIST
if [ "$CHROOT" = "Y" ] ; then
	
	# GRUB options in function to the guest architectures
	# grub-legacy (Nov 2024 - since Debian 13 "Trixie") becomes just a "transistional" (sic) package to grub-pc
	if [ "$( cat /tmp/guestarc | grep -a ' amd64 ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-cloud-amd64 $ESP grub-coreboot $ESP grub-efi-amd64 $ESP grub-efi-ia32 $ESP grub-ieee1275 $ESP grub-pc $ESP grub-xen $ESP grub-xen-host $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' armel ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-efi-arm $ESP grub-uboot $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' armhf ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-efi-arm $ESP grub-uboot $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' arm64 ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-efi-arm64 $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' hurd-i386 ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-coreboot $ESP grub-efi-ia32 $ESP grub-ieee1275 $ESP grub-pc $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' i386 ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-coreboot $ESP grub-efi-amd64 $ESP grub-efi-ia32 $ESP grub-ieee1275 $ESP grub-pc $ESP grub-xen $ESP grub-xen-host $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' ia64 ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-efi-ia64 $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' kfreebsd-amd64 ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-coreboot $ESP grub-efi-amd64 $ESP grub-efi-ia32 $ESP grub-ieee1275 $ESP grub-pc $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' kfreebsd-i386 ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-coreboot $ESP grub-efi-ia32 $ESP grub-ieee1275 $ESP grub-pc $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' loong64 ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-efi-loong64 $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' mipsel ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-yeeloong $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' powerpc ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-ieee1275 $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' ppc64el ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-ieee1275 $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' riscv64 ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-efi-riscv64 $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' sparc ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-ieee1275 $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' sparc64 ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-ieee1275 $ESP $GRUBVERLIST") ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' x32 ' )" != "" ] ; then GRUBVERLIST=$(printf "grub-coreboot $ESP grub-efi-amd64 $ESP grub-efi-ia32 $ESP grub-ieee1275 $ESP grub-pc $ESP $GRUBVERLIST") ; fi

	if [ "$GRUBVERLIST" = "" ] ; then
		cat /tmp/guestarc
		check_exit
	fi

	# Preselect a GRUB version as the default proposal
	unset PRESELGRUB
if [ "$EFIDET" != "" ] ; then
	if [ "$( cat /tmp/guestarc | grep -a ' amd64 ' )" != "" ] ; then PRESELGRUB="grub-efi-amd64" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' armel ' )" != "" ] ; then PRESELGRUB="grub-efi-arm" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' armhf ' )" != "" ] ; then PRESELGRUB="grub-efi-arm" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' arm64 ' )" != "" ] ; then PRESELGRUB="grub-efi-arm64" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' hurd-i386 ' )" != "" ] ; then PRESELGRUB="grub-efi-ia32" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' i386 ' )" != "" ] ; then PRESELGRUB="grub-efi-ia32" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' ia64 ' )" != "" ] ; then PRESELGRUB="grub-efi-ia64" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' kfreebsd-amd64 ' )" != "" ] ; then PRESELGRUB="grub-efi-amd64" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' kfreebsd-i386 ' )" != "" ] ; then PRESELGRUB="grub-efi-ia32" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' loong64 ' )" != "" ] ; then PRESELGRUB="grub-efi-loong64" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' mipsel ' )" != "" ] ; then PRESELGRUB="grub-yeeloong" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' powerpc ' )" != "" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' ppc64el ' )" != "" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' riscv64 ' )" != "" ] ; then PRESELGRUB="grub-efi-riscv64" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' sparc ' )" != "" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' sparc64 ' )" != "" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' x32 ' )" != "" ] ; then PRESELGRUB="grub-efi-amd64" ; fi
else
	if [ "$( cat /tmp/guestarc | grep -a ' amd64 ' )" != "" ] ; then PRESELGRUB="grub-pc" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' armel ' )" != "" ] ; then PRESELGRUB="grub-uboot" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' armhf ' )" != "" ] ; then PRESELGRUB="grub-uboot" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' arm64 ' )" != "" ] ; then PRESELGRUB="grub-efi-arm64" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' hurd-i386 ' )" != "" ] ; then PRESELGRUB="grub-pc" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' i386 ' )" != "" ] ; then PRESELGRUB="grub-pc" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' ia64 ' )" != "" ] ; then PRESELGRUB="grub-efi-ia64" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' kfreebsd-amd64 ' )" != "" ] ; then PRESELGRUB="grub-pc" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' kfreebsd-i386 ' )" != "" ] ; then PRESELGRUB="grub-pc" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' loong64 ' )" != "" ] ; then PRESELGRUB="grub-efi-loong64" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' mipsel ' )" != "" ] ; then PRESELGRUB="grub-yeeloong" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' powerpc ' )" != "" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' ppc64el ' )" != "" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' riscv64 ' )" != "" ] ; then PRESELGRUB="grub-efi-riscv64" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' sparc ' )" != "" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' sparc64 ' )" != "" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$( cat /tmp/guestarc | grep -a ' x32 ' )" != "" ] ; then PRESELGRUB="grub-pc" ; fi
fi

elif [ "$CHROOT" = "N" ] ; then
	
	# GRUB options in function to the active kernel
	# grub-legacy (Nov 2024 - since Debian 13 "Trixie") becomes just a "transistional" (sic) package to grub-pc
	if [ "$SYSARC" = "amd64" ] ; then GRUBVERLIST=$(printf "grub-cloud-amd64 $ESP grub-coreboot $ESP grub-efi-amd64 $ESP grub-efi-ia32 $ESP grub-ieee1275 $ESP grub-pc $ESP grub-xen $ESP grub-xen-host $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "armel" ] ; then GRUBVERLIST=$(printf "grub-efi-arm $ESP grub-uboot $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "armhf" ] ; then GRUBVERLIST=$(printf "grub-efi-arm $ESP grub-uboot $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "arm64" ] ; then GRUBVERLIST=$(printf "grub-efi-arm64 $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "hurd-i386" ] ; then GRUBVERLIST=$(printf "grub-coreboot $ESP grub-efi-ia32 $ESP grub-ieee1275 $ESP grub-pc $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "i386" ] ; then GRUBVERLIST=$(printf "grub-coreboot $ESP grub-efi-amd64 $ESP grub-efi-ia32 $ESP grub-ieee1275 $ESP grub-pc $ESP grub-xen $ESP grub-xen-host $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "ia64" ] ; then GRUBVERLIST=$(printf "grub-efi-ia64 $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "kfreebsd-amd64" ] ; then GRUBVERLIST=$(printf "grub-coreboot $ESP grub-efi-amd64 $ESP grub-efi-ia32 $ESP grub-ieee1275 $ESP grub-pc $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "kfreebsd-i386" ] ; then GRUBVERLIST=$(printf "grub-coreboot $ESP grub-efi-ia32 $ESP grub-ieee1275 $ESP grub-pc $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "loong64" ] ; then GRUBVERLIST=$(printf "grub-efi-loong64 $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "mipsel" ] ; then GRUBVERLIST=$(printf "grub-yeeloong $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "powerpc" ] ; then GRUBVERLIST=$(printf "grub-ieee1275 $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "ppc64el" ] ; then GRUBVERLIST=$(printf "grub-ieee1275 $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "riscv64" ] ; then GRUBVERLIST=$(printf "grub-efi-riscv64 $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "sparc" ] ; then GRUBVERLIST=$(printf "grub-ieee1275 $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "sparc64" ] ; then GRUBVERLIST=$(printf "grub-ieee1275 $ESP $GRUBVERLIST") ; fi
	if [ "$SYSARC" = "x32" ] ; then GRUBVERLIST=$(printf "grub-coreboot $ESP grub-efi-amd64 $ESP grub-efi-ia32 $ESP grub-ieee1275 $ESP grub-pc $ESP $GRUBVERLIST") ; fi

	if [ "$GRUBVERLIST" = "" ] ; then
		echo "ERROR: $(uname -mr) --- $(uname -a)"
		check_exit
	fi

	# Preselect a GRUB version as the default proposal
	unset PRESELGRUB
if [ "$EFIDET" != "" ] ; then
	if [ "$SYSARC" = "amd64" ] ; then PRESELGRUB="grub-efi-amd64" ; fi
	if [ "$SYSARC" = "armel" ] ; then PRESELGRUB="grub-efi-arm" ; fi
	if [ "$SYSARC" = "armhf" ] ; then PRESELGRUB="grub-efi-arm" ; fi
	if [ "$SYSARC" = "arm64" ] ; then PRESELGRUB="grub-efi-arm64" ; fi
	if [ "$SYSARC" = "hurd-i386" ] ; then PRESELGRUB="grub-efi-ia32" ; fi
	if [ "$SYSARC" = "i386" ] ; then PRESELGRUB="grub-efi-ia32" ; fi
	if [ "$SYSARC" = "ia64" ] ; then PRESELGRUB="grub-efi-ia64" ; fi
	if [ "$SYSARC" = "kfreebsd-amd64" ] ; then PRESELGRUB="grub-efi-amd64" ; fi
	if [ "$SYSARC" = "kfreebsd-i386" ] ; then PRESELGRUB="grub-efi-ia32" ; fi
	if [ "$SYSARC" = "loong64" ] ; then PRESELGRUB="grub-efi-loong64" ; fi
	if [ "$SYSARC" = "mipsel" ] ; then PRESELGRUB="grub-yeeloong" ; fi
	if [ "$SYSARC" = "powerpc" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$SYSARC" = "ppc64el" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$SYSARC" = "riscv64" ] ; then PRESELGRUB="grub-efi-riscv64" ; fi
	if [ "$SYSARC" = "sparc" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$SYSARC" = "sparc64" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$SYSARC" = "x32" ] ; then PRESELGRUB="grub-efi-amd64" ; fi
else
	if [ "$SYSARC" = "amd64" ] ; then PRESELGRUB="grub-pc" ; fi
	if [ "$SYSARC" = "armel" ] ; then PRESELGRUB="grub-uboot" ; fi
	if [ "$SYSARC" = "armhf" ] ; then PRESELGRUB="grub-uboot" ; fi
	if [ "$SYSARC" = "arm64" ] ; then PRESELGRUB="grub-efi-arm64" ; fi
	if [ "$SYSARC" = "hurd-i386" ] ; then PRESELGRUB="grub-pc" ; fi
	if [ "$SYSARC" = "i386" ] ; then PRESELGRUB="grub-pc" ; fi
	if [ "$SYSARC" = "ia64" ] ; then PRESELGRUB="grub-efi-ia64" ; fi
	if [ "$SYSARC" = "kfreebsd-amd64" ] ; then PRESELGRUB="grub-pc" ; fi
	if [ "$SYSARC" = "kfreebsd-i386" ] ; then PRESELGRUB="grub-pc" ; fi
	if [ "$SYSARC" = "loong64" ] ; then PRESELGRUB="grub-efi-loong64" ; fi
	if [ "$SYSARC" = "mipsel" ] ; then PRESELGRUB="grub-yeeloong" ; fi
	if [ "$SYSARC" = "powerpc" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$SYSARC" = "ppc64el" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$SYSARC" = "riscv64" ] ; then PRESELGRUB="grub-efi-riscv64" ; fi
	if [ "$SYSARC" = "sparc" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$SYSARC" = "sparc64" ] ; then PRESELGRUB="grub-ieee1275" ; fi
	if [ "$SYSARC" = "x32" ] ; then PRESELGRUB="grub-pc" ; fi
fi

else
	check_exit
fi


sel_grub () {

EFIGRUBVERIN=$(echo "$GRUBVERIN" | grep -aEi '\-efi' )

if [ "$EFIPARTFSTAB" != "" ] ; then
	# EFI
	if [ "$EFIGRUBVERIN" != "" ] ; then
		EFIGRUBTEXT=$"The installed system seems to be configured as EFI, if so grub-efi must be selected, $GRUBVERIN is probably a good choice."
#		PRESELGRUB=$GRUBVERIN
	else
		EFIGRUBTEXT=$"The installed system seems to be configured as EFI, if so grub-efi must be selected."
	fi
else
	# No EFI
	if [ "$EFIGRUBVERIN" != "" ] ; then
		EFIGRUBTEXT=$"This computer seems not to have EFI, if so a non-efi GRUB version must be selected, for example grub-pc for computers with BIOS (grub-coreboot for GNU Boot / Canoeboot / CoreBoot / LinuxBIOS, grub-ieee1275 for OpenFirmware / OpenBoot / OpenBIOS,...)."
	else
		EFIGRUBTEXT=$"This computer seems not to have EFI, if so a non-efi GRUB version must be selected, $GRUBVERIN is probably a good choice."
#		PRESELGRUB=$GRUBVERIN
	fi
fi

if [ "$CHROOT" = "N" ] ; then
	GRUBSELTEXT=$"Please select the GRUB version to install.\n\nThe installed system has $GRUBVERIN as GRUB version.\n\n$EFIGRUBTEXT \n\nIf in doubt, select $PRESELGRUB (the first on the list).\n"
elif [ "$CHROOT" = "Y" ] ; then
	GRUBSELTEXT=$"Please select the GRUB version to install.\n\nThe installed system has $GRUBVERIN as GRUB version.\n\nThe system in operation has $GRUBVERH as GRUB version.\n\n$EFIGRUBTEXT \n\nIf in doubt, select $PRESELGRUB (the first on the list).\n"
else
	check_exit
fi

GRUBVERSEL=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT "$GRUBSELTEXT" $H $W $LH $COLUMN $COLUMN $PRESELGRUB " " $(echo "$GRUBVERLIST" | sed "s|$PRESELGRUB $ESP ||g") | head -n 1 )

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

	if [ "$GRUBVERSEL" = "" ] ; then
	REFUN=sel_grub
	input_error ; return
	fi

echo "GRUBVERSEL=\"$GRUBVERSEL\"" | tee -a $DTMP/lsvar

}


check_efifstab () {

EFIGRUBVERSEL=$(echo "$GRUBVERSEL" | grep -aEi '\-efi' )
if [ "$EFIGRUBVERSEL" != "" ] && [ "$EFIPARTFSTAB" = "" ] ; then
	$DIALOG $WICON $WTITLE "$TITLE" $WYN   $WTEXT $"It seems that there is no EFI partition (ESP) configured in /etc/fstab. GRUB recovery will likely fail.\n\nDo you want to continue?" $H $W
		if [ "$?" -ne 0 ] ; then
		sel_grub
		fi
fi

}

config_grub () {

if [ -e "$DTMP/etc/grubil" ] ; then
	$DIALOG $WICON $WTITLE "$TITLE" $INFO  $WTEXT "$(cat "$DTMP/etc/grubil" | grep -aEiv "=====")" $H $W
fi

SELGRUBINSLOC=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"Please select where to install GRUB.\n\n'Installation disk' is usually a right choice, but 'First internal disk' may be a right option if the operating system is installed to a secondary disk other than the main disk (the boot order or priority of the disks can be set in BIOS/EFI).\n\nPlease select an option:" $H $W $LH $COLUMN $COLUMN $"Installation disk" " " $"First internal disk" " " $"Select disk" " " $"Installation partition" " " $"Stop now" " " | head -n 1 )

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

	if [ "$SELGRUBINSLOC" = "" ] ; then
	REFUN=config_grub
	input_error ; return
	fi

case "$SELGRUBINSLOC" in

	$"Installation disk")
		GRUBINSLOC=$(lsblk -r -n -o KNAME,TYPE -s $OBJSYSPART | grep -aEi ' disk' | awk '{print "/dev/"$1}' | sort -u)
	;;

	$"First internal disk")
		if [ "$(lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' disk' | awk '{print "/dev/"$1}' | grep -a /dev/nvme0n1)" != "" ] ; then
			GRUBINSLOC="/dev/nvme0n1"
		elif [ "$(lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' disk' | awk '{print "/dev/"$1}' | grep -a /dev/sda)" != "" ] ; then
			GRUBINSLOC="/dev/sda"
		elif [ "$(lsblk -r -n -o KNAME,RM,TYPE | grep -aEi ' disk' | awk '{print "/dev/"$1}' | grep -a /dev/mmcblk0)" != "" ] ; then
			GRUBINSLOC="/dev/mmcblk0"
		else
			REFUN=config_grub
			input_error ; return
		fi
	;;

	$"Select disk")
		ALLDEVS=$"List all devices (only for experts)"
		INTDEVS=$"List only internal devices"
INT=0
ADDOPT="$ALLDEVS"
seldis () {
		DISKLISTSIZE=$(lsblk -r -n -o KNAME,RM,SIZE,TYPE | grep -aEi " $INT " | grep -aEi ' disk' | awk '{print "'"$PRE"'","/dev/"$1"\t("$3")","'"$POST"'"}' | sort -u )
		PRE_GRUBINSLOC=$($DIALOG $WICON $WTITLE "$TITLE" $MULTIPLELIST $WTEXT $"Select disk:" $H $W $LH $COLUMN $COLUMN $COLUMN $DISKLISTSIZE $PRE "$ADDOPT" " " $POST | sed 's|(.*)||g' | sed 's|^TRUE||g')
		if [ "$?" -ne 0 ] || [ "$PRE_GRUBINSLOC" = "" ] ; then
			REFUN=config_grub
			input_error ; return
		fi
		if [ "$(echo $PRE_GRUBINSLOC | grep -a "$(echo $ALLDEVS | sed 's| (.*)||g')")" != "" ] ; then
			INT=.
			ADDOPT="$INTDEVS"
			seldis
			return
		fi
		if [ "$(echo $PRE_GRUBINSLOC | grep -a "$(echo $INTDEVS | sed 's| (.*)||g')")" != "" ] ; then
			INT=0
			ADDOPT="$ALLDEVS"
			seldis
			return
		fi
}
		seldis || return 1
		GRUBINSLOC="$PRE_GRUBINSLOC"
	;;

	$"Installation partition")
		GRUBINSLOC="part"
	;;

	$"Stop now")
		exit 0
	;;

	*)
	echo "ERROR: SELGRUBINSLOC=$SELGRUBINSLOC"
	check_exit
	;;

esac

echo "GRUBINSLOC=\"$GRUBINSLOC\"" | tee -a $DTMP/lsvar

}

sel_grub
check_efifstab
config_grub


### PRE-DOWNLOAD OF GRUB PACKAGES ########################################
#
#if [ "$CHROOT" = "Y" ] ; then
#	if   [ "$CHROOTNATIV" = "Y" ] ; then
#		apt-get -d install $GRUBVERSEL os-prober
#	elif [ "$CHROOTNATIV" = "N" ] ; then
#		dpkg --add-architecture "$SYSARC"
#		apt-get update
#		apt-get -d install ${GRUBVERSEL}:${SYSARC} os-prober:${SYSARC}
#	else
#		check_exit
#	fi
#
#	# copy
#	ls /var/cache/apt/archives/ | grep -aEi "^grub|^os-prober" | sed 's|_.*||g' | while read i ; do
#		if [ -e $DTMP/var/cache/apt/archives ] ; then
#			if [ "$(ls $DTMP/var/cache/apt/archives/ | grep -aEi ^${i}_ )" = "" ] ; then
#				cp -v /var/cache/apt/archives/${i}_* $DTMP/var/cache/apt/archives/
#			fi
#		else
#			check_exit
#		fi
#	done
#
#elif [ "$CHROOT" = "N" ] ; then
#	true
#else
#	check_exit
#fi


### CHROOTSCRIPT ########################################

os-prober

if [ "$CHROOT" = "Y" ] ; then
	# Internet chroot
	mv $DTMP/etc/resolv.conf $DTMP/etc/resolv.conf_ORIG
	rm -f $DTMP/etc/resolv.conf
	cp -Lpv --remove-destination /etc/resolv.conf $DTMP/etc/resolv.conf
fi

# chrootscript
EOF=EOF

#cat << EOF > $DTMP/chrootscript
cat > $DTMP/chrootscript <<EOF
#!/bin/bash

CNAME=$CNAME
VERSION=$VERSION
TITLE=$TITLE

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

ERRORLOG="/chroot.log"
#if [ -e "\$ERRORLOG" ] ; then
#	mv -f \$ERRORLOG \${ERRORLOG}.ant
#fi
#if [ -e "\$ERRORLOG" ] ; then rm -rf "\$ERRORLOG" ; fi

if [ "$DEBUG" = "Y" ] ; then
	set -xv
fi
if [ "$DEBUG" != "N" ] ; then
exec > >(tee -a "\$ERRORLOG") 2>&1
echo "\$0" "\$*" >> "\$ERRORLOG"
echo "env:" >> "\$ERRORLOG"
env >> "\$ERRORLOG"
echo "set:" >> "\$ERRORLOG"
set >> "\$ERRORLOG"
fi

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

cat /lsvar

source /lsvar

#udevadm control --reload-rules && udevadm trigger -v
mount -a

# INTERNET ########################################

if [ "\$CHROOT" = "Y" ] ; then
	# Caution: In networking, restart =/= stop & start
	if [ "\$(command -v systemctl)" != "" ] ; then
		systemctl stop systemd-networkd
		systemctl start systemd-networkd
	fi

	if [ "\$(command -v service)" != "" ] ; then
		service networking stop
		service networking start
	fi

	if [ -e "/etc/init.d/networking" ] ; then
		/etc/init.d/networking stop
		/etc/init.d/networking start
	fi
fi

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

# Install GRUB - P1 ########################################

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
REST_GRUB_THEME=\$(cat /etc/default/grub | grep -aEi ^GRUB_THEME=)

os-prober

find /boot/grub/ -type f | while read i ; do rm -f "\$i" ; done
mkdir -pv /boot/grub/

EFIGRUBVERSEL=\$(echo "\$GRUBVERSEL" | grep -aEi '\-efi' )
if [ "\$EFIGRUBVERSEL" != "" ] ; then
	mkdir -pv /boot/efi/
	mkdir -pv \$EFIPARTFSTAB
	mkdir -pv /boot/efi/EFI/
#	mkdir -pv /boot/efi/EFI/picalibre/
#	mkdir -pv /boot/efi/EFI/devuan/
#	mkdir -pv /boot/efi/EFI/debian/
fi

case "\$GRUBVERSEL" in

	grub-gfxboot)
#	if [ "\$GRUBVERIN" != "\$GRUBVERSEL" ] ; then
		if [ "\$(ls /var/cache/apt/archives/ | grep -aEi ^\${GRUBVERSEL}_.*_\${SYSARC}.deb )" != "" ] && [ "\$TESTINTERNET" = "N" ] ; then
			#ls /var/cache/apt/archives/ | grep -aEi ^grub | sed 's|_.*||g' | while read i ; do DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^\$i ; done
			DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^\${GRUBVERIN}
			DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^grub2 ^grub-pc efibootmgr
			cd /var/cache/apt/archives/
			dpkg -i \$(ls | grep -aEi ^grub-common_.*_\${SYSARC}.deb | sort -Vr | head -n 1 )
			#for i in \$(dpkg -I \${GRUBVERSEL}-bin_*_\${SYSARC}.deb     | grep -aE 'Depend:|Depends:' | sed 's|,| |g' | sed 's| |\n|g' | grep -aEi ^grub | cut -d ' ' -f 1 | sort -u ) ; do dpkg -i \$(ls | grep -aEi ^\${i}_.*_\${SYSARC}.deb | sort -Vr | head -n 1 ) ; done
			for i in \$(dpkg -I \${GRUBVERSEL}_*_\${SYSARC}.deb    | grep -aE 'Depend:|Depends:' | sed 's|,| |g' | sed 's| |\n|g' | grep -aEi ^grub | cut -d ' ' -f 1 | sort -u ) ; do dpkg -i \$(ls | grep -aEi ^\${i}_.*_\${SYSARC}.deb | sort -Vr | head -n 1 ) ; done
			dpkg -i \$(ls | grep -aEi ^\${GRUBVERSEL}_.*_\${SYSARC}.deb | sort -Vr | head -n 1 )
			cd - 1>/dev/null
		elif [ "\$TESTINTERNET" = "Y" ] ; then
			apt-get update -y
			DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^\${GRUBVERIN}
			DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^grub2 ^grub-pc efibootmgr
		
			if [ "\$(apt-cache showpkg grub-gfxboot)" != "" ] ; then
				for i in \$GRUBVERSEL grub-common os-prober ; do DEBIAN_FRONTEND=noninteractive apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" \$i ; done
			else
				DEBIAN_FRONTEND=noninteractive apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" grub-common os-prober
				cd /var/cache/apt/archives/
				
				wget https://deb.picalibre.org/pool/main/gen/g/grub-gfxboot/grub-gfxboot_0.97-48+1_\${SYSARC}.deb
				if [ "\$?" -ne 0 ] ; then
					check_exit
				fi
				dpkg -i grub-gfxboot_*_\${SYSARC}.deb
					if [ ! -e /boot/grub/menu.lst ] ; then
					dpkg -i grub-gfxboot_*_\${SYSARC}.deb
					fi
				
				cd - 1>/dev/null
		
			fi
		else
			echo "No Internet, no .deb"
		fi
#	fi
	;;

	grub-legacy)
#	if [ "\$GRUBVERIN" != "\$GRUBVERSEL" ] ; then
		if [ "\$(ls /var/cache/apt/archives/ | grep -aEi ^\${GRUBVERSEL}_.*_\${SYSARC}.deb )" != "" ] && [ "\$TESTINTERNET" = "N" ] ; then
			#ls /var/cache/apt/archives/ | grep -aEi ^grub | sed 's|_.*||g' | while read i ; do DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^\$i ; done
			DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^\${GRUBVERIN}
			DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^grub2 ^grub-pc efibootmgr
			cd /var/cache/apt/archives/
			dpkg -i \$(ls | grep -aEi ^grub-common_.*_\${SYSARC}.deb | sort -Vr | head -n 1 )
			#for i in \$(dpkg -I \${GRUBVERSEL}-bin_*_\${SYSARC}.deb     | grep -aE 'Depend:|Depends:' | sed 's|,| |g' | sed 's| |\n|g' | grep -aEi ^grub | cut -d ' ' -f 1 | sort -u ) ; do dpkg -i \$(ls | grep -aEi ^\${i}_.*_\${SYSARC}.deb | sort -Vr | head -n 1 ) ; done
			for i in \$(dpkg -I \${GRUBVERSEL}_*_\${SYSARC}.deb    | grep -aE 'Depend:|Depends:' | sed 's|,| |g' | sed 's| |\n|g' | grep -aEi ^grub | cut -d ' ' -f 1 | sort -u ) ; do dpkg -i \$(ls | grep -aEi ^\${i}_.*_\${SYSARC}.deb | sort -Vr | head -n 1 ) ; done
			dpkg -i \$(ls | grep -aEi ^\${GRUBVERSEL}_.*_\${SYSARC}.deb | sort -Vr | head -n 1 )
			cd - 1>/dev/null
		elif [ "\$TESTINTERNET" = "Y" ] ; then
			apt-get update -y
			DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^\${GRUBVERIN}
			DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^grub2 ^grub-pc efibootmgr
			for i in \$GRUBVERSEL grub-common os-prober ; do DEBIAN_FRONTEND=noninteractive apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" \$i ; done
		else
			echo "No Internet, no .deb"
		fi
#	fi
	;;

	grub-efi-amd64|grub-efi-arm|grub-efi-arm64|grub-efi-ia32|grub-efi-ia64|grub-efi-riscv64|grub-efi-loong64)
#	if [ "\$GRUBVERIN" != "\$GRUBVERSEL" ] ; then
		if [ "\$(ls /var/cache/apt/archives/ | grep -aEi ^\${GRUBVERSEL}_.*_\${SYSARC}.deb )" != "" ] && [ "\$TESTINTERNET" = "N" ] ; then
			#ls /var/cache/apt/archives/ | grep -aEi ^grub | sed 's|_.*||g' | while read i ; do DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^\$i ; done
			DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^\${GRUBVERIN}
			cd /var/cache/apt/archives/
			dpkg -i \$(ls | grep -aEi ^grub-common_.*_\${SYSARC}.deb | sort -Vr | head -n 1 )
			dpkg -i \$(ls | grep -aEi ^grub2-common_.*_\${SYSARC}.deb | sort -Vr | head -n 1 )
			for i in \$(dpkg -I \${GRUBVERSEL}-bin_*_\${SYSARC}.deb     | grep -aE 'Depend:|Depends:' | sed 's|,| |g' | sed 's| |\n|g' | grep -aEi ^grub | cut -d ' ' -f 1 | sort -u ) ; do dpkg -i \$(ls | grep -aEi ^\${i}_.*_\${SYSARC}.deb | sort -Vr | head -n 1 ) ; done
			for i in \$(dpkg -I \${GRUBVERSEL}_*_\${SYSARC}.deb    | grep -aE 'Depend:|Depends:' | sed 's|,| |g' | sed 's| |\n|g' | grep -aEi ^grub | cut -d ' ' -f 1 | sort -u ) ; do dpkg -i \$(ls | grep -aEi ^\${i}_.*_\${SYSARC}.deb | sort -Vr | head -n 1 ) ; done
			dpkg -i \$(ls | grep -aEi ^\${GRUBVERSEL}_.*_\${SYSARC}.deb | sort -Vr | head -n 1 ) \$(ls | grep -aEi ^\${GRUBVERSEL}-bin_.*_\${SYSARC}.deb | sort -Vr | head -n 1 )
			if [ "\$(ls /var/cache/apt/archives/ | grep -aEi ^\${GRUBVERSEL}-signed_.*_\${SYSARC}.deb )" != "" ] ; then
			dpkg -i \$(ls | grep -aEi ^\${GRUBVERSEL}-signed_.*_\${SYSARC}.deb | sort -Vr | head -n 1 )
			fi
			cd - 1>/dev/null
		elif [ "\$TESTINTERNET" = "Y" ] ; then
			apt-get update -y
			DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^\${GRUBVERIN}
			for i in \$GRUBVERSEL \${GRUBVERSEL}-signed \${GRUBVERSEL}-bin grub-common grub2-common os-prober ; do DEBIAN_FRONTEND=noninteractive apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" \$i ; done
			DEBIAN_FRONTEND=noninteractive apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" efibootmgr
		else
			echo "No Internet, no .deb"
		fi
#	fi
	;;

	grub-cloud-amd64|grub-coreboot|grub-ieee1275|grub-pc|grub-uboot|grub-xen|grub-xen-host|grub-yeeloong)
#	if [ "\$GRUBVERIN" != "\$GRUBVERSEL" ] ; then
		if [ "\$(ls /var/cache/apt/archives/ | grep -aEi ^\${GRUBVERSEL}_.*_\${SYSARC}.deb )" != "" ] && [ "\$TESTINTERNET" = "N" ] ; then
			#ls /var/cache/apt/archives/ | grep -aEi ^grub | sed 's|_.*||g' | while read i ; do DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^\$i ; done
			DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^\${GRUBVERIN}
			DEBIAN_FRONTEND=noninteractive apt-get purge -y efibootmgr
			cd /var/cache/apt/archives/
			dpkg -i \$(ls | grep -aEi ^grub-common_.*_\${SYSARC}.deb | sort -Vr | head -n 1 )
			dpkg -i \$(ls | grep -aEi ^grub2-common_.*_\${SYSARC}.deb | sort -Vr | head -n 1 )
			for i in \$(dpkg -I \${GRUBVERSEL}-bin_*_\${SYSARC}.deb     | grep -aE 'Depend:|Depends:' | sed 's|,| |g' | sed 's| |\n|g' | grep -aEi ^grub | cut -d ' ' -f 1 | sort -u ) ; do dpkg -i \$(ls | grep -aEi ^\${i}_.*_\${SYSARC}.deb | sort -Vr | head -n 1 ) ; done
			for i in \$(dpkg -I \${GRUBVERSEL}_*_\${SYSARC}.deb    | grep -aE 'Depend:|Depends:' | sed 's|,| |g' | sed 's| |\n|g' | grep -aEi ^grub | cut -d ' ' -f 1 | sort -u ) ; do dpkg -i \$(ls | grep -aEi ^\${i}_.*_\${SYSARC}.deb | sort -Vr | head -n 1 ) ; done
			dpkg -i \$(ls | grep -aEi ^\${GRUBVERSEL}_.*_\${SYSARC}.deb | sort -Vr | head -n 1 ) \$(ls | grep -aEi ^\${GRUBVERSEL}-bin_.*_\${SYSARC}.deb | sort -Vr | head -n 1 )
			cd - 1>/dev/null
		elif [ "\$TESTINTERNET" = "Y" ] ; then
			apt-get update -y
			DEBIAN_FRONTEND=noninteractive apt-get purge -y --allow-remove-essential ^\${GRUBVERIN}
			DEBIAN_FRONTEND=noninteractive apt-get purge -y efibootmgr
			for i in \$GRUBVERSEL \${GRUBVERSEL}-bin grub-common grub2-common os-prober ; do DEBIAN_FRONTEND=noninteractive apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" \$i ; done
		else
			echo "No Internet, no .deb"
		fi
#	fi
	;;

	*)
	echo "ERROR: GRUBVERSEL = \$GRUBVERSEL "
	;;

esac

# Ensure the installation was satisfactory.
dpkg --configure -a


# Install GRUB - P2 ########################################

if [ "\$(cat /etc/default/grub | grep -aEi ^GRUB_ENABLE_CRYPTODISK=)" = "" ] ; then
	echo " " >> /etc/default/grub
	echo "GRUB_ENABLE_CRYPTODISK=y" >> /etc/default/grub
else
	sed -i "s|^GRUB_ENABLE_CRYPTODISK.*|GRUB_ENABLE_CRYPTODISK=y|g" /etc/default/grub
fi
# https://cryptsetup-team.pages.debian.net/cryptsetup/encrypted-boot.html#avoiding-the-extra-password-prompt

if [ "\$REST_GRUB_THEME" != "" ] && [ "\$(cat /etc/default/grub | grep -aEi ^GRUB_THEME=)" = "" ] ; then
echo >> /etc/default/grub
echo \$REST_GRUB_THEME >> /etc/default/grub
echo >> /etc/default/grub
fi

if [ "\$REST_GRUB_DEFAULT" != "" ] ; 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


# grub-legacy shell does not work if grub files are not in /boot

echo "os-prober (1)"
os-prober


# RAID #####

## Open all existing encrypted volumes WITH headers:
#for i in \$(lsblk -r -n -o KNAME,RM,FSTYPE | grep -aEi 'crypt' | awk '{print "/dev/"\$1}' | sort -u ) ; do lsblk -r -n -o KNAME,SIZE,LABEL,UUID | grep -aE "^\$(echo \$i | sed 's|/dev/||g') " ; cryptsetup luksOpen \$i e\$(echo \$i | sed 's|/dev/||g') ; done

## Activate existing LVM:
#vgchange -ay

## Activate existing RAID:
#mdadm --assemble --scan

#if [ -e /GRUBRAID ] ; then rm -rf /GRUBRAID ; fi
#
#if [ "\$(echo \$GRUBINSLOC | grep -a '/dev/')" != "" ] ; then
#	if [ "\$(command -v mdadm)" != "" ] ; then
#		mdadm --detail \$OBJSYSPART | grep -a " /dev/" | awk '{print \$NF}' | grep -aEio ".*[a-zA-Z]" | sort -u -r | while read PREINSTALLDISK ; do
#				# fix around (mmc)blk devices with (mmc)blkXpY partitions (e.g. /dev/mmcblk0p1 ) and NVME devices with nvmeXnYpZ partitions (e.g. /dev/nvme0n1p1 ):
#				CHECK_PREINSTALLDISK=\$(echo "\$PREINSTALLDISK" | grep -aEi "[0-9]p$")
#				if [ "\$CHECK_PREINSTALLDISK" != "" ] ; then
#					INSTALLDISK=\$(echo "\$PREINSTALLDISK" | sed "s|p$||g")
#				else
#					INSTALLDISK=\$PREINSTALLDISK
#				fi
#			#fi
#			grub-install \$INSTALLDISK
#			if [ "\$?" -ne 0 ] ; then
#				grub-install --directory /usr/lib/grub/\$(ls -p /usr/lib/grub/ | grep -a / | tail -n 1) \$INSTALLDISK
#			fi
#			if [ "\$?" -eq 0 ] ; then
#				echo \$INSTALLDISK >> /GRUBRAID
#			fi
#		done
#	fi
#fi

# GRUBINSLOC #####

if [ -e /GRUBERROR ] ; then rm -rf /GRUBERROR ; fi

if [ "\$(echo \$GRUBINSLOC | grep -a '/dev/')" != "" ] ; then
	for i in \$GRUBINSLOC ; do
		echo "GRUB install \$i"
		grub-install \$i
		if [ "\$?" -ne 0 ] ; then
			grub-install --directory /usr/lib/grub/\$(ls -p /usr/lib/grub/ | grep -a / | tail -n 1) \$i
			if [ "\$?" -ne 0 ] ; then
#			if [ "\$?" -ne 0 ] && [ ! -e /GRUBRAID ] ; then
				echo "GRUBERROR=\"Y\"" > /GRUBERROR
			fi
		fi
	done
fi

#if [ -e /GRUBRAID ] ; then cat /GRUBRAID ; rm -rf /GRUBRAID ; fi

if [ "\$GRUBINSLOC" = "part" ] ; then

	if [ "\$GRUBVERSEL" = "grub-legacy" ] || [ "\$GRUBVERSEL" = "grub-gfxboot" ] ; then
	
		# grub-install fails to a partition: "error 22: No such partition"
	
		# The following command will probable give error 22 but gets the files in /boot (grub shell might not)
		grub-install \$OBJSYSPART
	
		# isolate the disk name and translate to the right number for grub
			# fix around (mmc)blk devices with (mmc)blkXpY partitions (e.g. /dev/mmcblk0p1 ) and NVME devices with nvmeXnYpZ partitions (e.g. /dev/nvme0n1p1 ):
			CHECK_OBJSYSPART_P=\$(echo \$OBJSYSPART | grep -aEi "[0-9]p[0-9]")
			if [ "\$CHECK_OBJSYSPART_P" != "" ] ; then
				CHECK_OBJSYSPART_N=\$(echo \$OBJSYSPART | grep -aEi "[0-9]n[0-9]")
				if [ "\$CHECK_OBJSYSPART_N" != "" ] ; then
					GRUBDEVNUM=\$(expr \$(echo \$OBJSYSPART | sed "s|p[0-9].*||g" | sed "s|.*[a-zA-Z/:-]||g" ) - 1 )
				else
					GRUBDEVNUM=\$(echo \$OBJSYSPART | sed "s|p[0-9].*||g" | sed "s|.*[a-zA-Z/:-]||g")
				fi
			else
				GRUBDEVNUM=\$(echo \$OBJSYSPART | sed 's|-||g' | cut -c 8 | tr "[a-j]" "[0-9]")
			fi
	
		# isolate the partition number
		OBJPARTNUM=\$(echo \$OBJSYSPART | sed "s|.*[a-zA-Z/:-]||g")
	
		# and reduce it by 1 for grub-1
		GRUBPARTNUM=\$(expr \$OBJPARTNUM - 1 )
	
		# finally get the finished grub root syntax
		GRUBROOT="(hd\$GRUBDEVNUM,\$GRUBPARTNUM)"
		echo "GRUBROOT=\"\$GRUBROOT\"" | tee -a /lsvar
	
		# use grub shell in batch mode (grub-install fails to a partition)
		echo "grub-batch"
#		grub --batch <<-$EOF
grub --batch <<$EOF
root \$GRUBROOT
setup \$GRUBROOT
quit
$EOF
	else
		grub-install \$OBJSYSPART
		if [ "\$?" -ne 0 ] ; then
			grub-install --recheck --no-floppy --force --directory /usr/lib/grub/\$(ls -p /usr/lib/grub/ | grep -a / | tail -n 1) \$OBJSYSPART
			if [ "\$?" -ne 0 ] ; then
				echo "GRUBERROR=\"Y\"" > /GRUBERROR
			fi
		fi
	fi
fi

echo "os-prober (2)"
os-prober

### NOMODESET OPTION ########################################

if [ "\$NOMODESETCHECK" = "" ] ; then
	NOMODESETCHECK=\$(cat /proc/cmdline | grep -aEio nomodeset )
fi

if [ "\$NOMODESETCHECK" != "" ] ; then
	if [ -e "/etc/default/grub" ] ; then
		sed -i '/^GRUB_CMDLINE_LINUX="/ s|"\$| nomodeset i915.modeset=0 nouveau.modeset=0 nvidia.modeset=0 radeon.modeset=0 amdgpu.modeset=0 vga=normal"|g' /etc/default/grub
		sed -i '/^GRUB_CMDLINE_LINUX="/ s|GRUB_CMDLINE_LINUX=" nomodeset i915.modeset=0 nouveau.modeset=0 nvidia.modeset=0 radeon.modeset=0 amdgpu.modeset=0 vga=normal"|GRUB_CMDLINE_LINUX="nomodeset i915.modeset=0 nouveau.modeset=0 nvidia.modeset=0 radeon.modeset=0 amdgpu.modeset=0 vga=normal"|g' /etc/default/grub
		cat /etc/default/grub | grep -aEi GRUB_CMDLINE_LINUX
	fi
fi

#if [ "\$GRUBVERSEL" = "grub-legacy" ] || [ "\$GRUBVERSEL" = "grub-gfxboot" ] ; then
#	true
#else
#	grub-mkconfig -o /boot/grub/grub.cfg
#	if [ "\$?" -ne 0 ] ; then
#		grub-mkconfig -o /boot/grub/grub.cfg
#		if [ "\$?" -ne 0 ] ; then
#			echo "GRUBERROR=\"Y\"" > /GRUBERROR
#		fi
#	fi
#fi

echo "update-grub"
update-grub
if [ "\$?" -ne 0 ] ; then
	update-grub
	if [ "\$?" -ne 0 ] ; then
		echo "GRUBERROR=\"Y\"" > /GRUBERROR
	fi
fi

## update-grub-legacy IF EXISTS
if [ "\$GRUBVERSEL" = "grub-legacy" ] || [ "\$GRUBVERSEL" = "grub-gfxboot" ] ; then
	if [ -f update-grub-legacy ] ; then
		echo "update legacy"
		bash update-grub-legacy /boot/grub/menu.lst
		rm update-grub-legacy
	fi
fi

# for EFI only
EFIGRUBVERSEL=\$(echo "\$GRUBVERSEL" | grep -aEi '\-efi' )
if [ "\$EFIGRUBVERSEL" != "" ] ; then
	find /boot/efi/EFI/
	ls -FAl --full-time /boot/efi/EFI/
	ls -FAl --full-time /boot/efi/EFI/*/*
	find /boot/efi/EFI/ -type f | while read i ; do file "\$i" ; done
	efibootmgr --verbose

if [ ! -e /boot/efi/EFI/boot ] && [ ! -e /boot/efi/EFI/BOOT ] ; then
	mkdir -pv /boot/efi/EFI/boot
fi

BOOTPATH=/boot/efi/EFI/\$(ls -p /boot/efi/EFI/ | grep -a / | grep -aEi boot | sort -u | tail -n 1)

cpgrubtoboot () {
	for DISTRO in picalibre PICALIBRE devuan DEVUAN debian DEBIAN ; do
		BOOTGRUB=\$(ls /boot/efi/EFI/\$DISTRO/ | grep -aEi grub | grep -aEiv grubnet)
		if [ "\$BOOTGRUB" != "" ] ; then
			for i in \$BOOTGRUB ; do
				if [ "\$(echo \$i | grep -aEi "\.cfg$")" != "" ] ; then
					cp -av --remove-destination /boot/efi/EFI/\$DISTRO/\$i \$BOOTPATH/\$i
				else
					cp -av --remove-destination /boot/efi/EFI/\$DISTRO/\$i \$BOOTPATH/\$(echo \$i | sed 's|grub|boot|g')
				fi
				echo /boot/efi/EFI/\$DISTRO/\$i | tee -a /etc/grub-efi-boot
			done
			cat /etc/grub-efi-boot | sort -u -o /etc/grub-efi-boot
			break
		fi
	done
}

cpgrubtoboot

# efibootmgr
NPARTOS=\$(efibootmgr --verbose | grep -aEi picalibre | awk '{print \$1}' | tr -cd "[0-9]")
VORD=\$(efibootmgr --verbose | grep -aEi "^BootOrder" | awk '{print \$2}')
if [ "\$NPARTOS" != "" ] && [ "\$VORD" != "" ] ; then
	efibootmgr -o \$NPARTOS,\$(echo \$VORD | sed "s|\$NPARTOS,||g" | sed "s|,\$NPARTOS\$||g")
	if [ "\$?" -eq 0 ] ; then
		efibootmgr -O
		efibootmgr -o \$NPARTOS,\$(echo \$VORD | sed "s|\$NPARTOS,||g" | sed "s|,\$NPARTOS\$||g")
	fi
efibootmgr --verbose
fi

for i in debian DEBIAN devuan DEVUAN ; do
	if [ -e /boot/efi/EFI/\$i/ ] ; then rmdir /boot/efi/EFI/\$i/ ; fi
done

# End: if [ "\$EFIGRUBVERSEL" != "" ]
fi

EOF


chmod +x $DTMP/chrootscript

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

#	if [ "$GRUBVERSEL" = "grub-legacy" ] || [ "$GRUBVERSEL" = "grub-gfxboot" ] ; then
#		if [ -f $LIBDEP/grub-batch ]         ; then cp -a $LIBDEP/grub-batch         $DTMP/grub-batch         ; fi
#		if [ -f $LIBDEP/update-grub-legacy ] ; then cp -a $LIBDEP/update-grub-legacy $DTMP/update-grub-legacy ; fi
#	fi

	if [ "$CHROOTNATIV" = "Y" ] ; then
		TT="$TITLE" ; COM="chroot $DTMP $(command -v bash) /chrootscript" ; TERMINAL
	elif [ "$CHROOTNATIV" = "N" ] ; then
		#chroot: failed to run command ‘/bin/bash’: Exec format error
		#update-binfmts --importdir /var/lib/binfmts/ --import
#		qemuarc
#		if [ "$(command -v qemu-${QEMUARC}-static)" = "" ] ; then
#			$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"You need to install install qemu-user-static or qemu-user-binfmt, and binfmt-support, before using $TITLE." $H $W
#			exit 1
#		fi
#		if [ ! -e "${DTMP}$(command -v qemu-${QEMUARC}-static)" ] ; then
#			cp -v $(command -v qemu-${QEMUARC}-static) ${DTMP}$(command -v qemu-${QEMUARC}-static)
#		else
#			QEMUDEL="N"
#		fi
		TT="$TITLE" ; COM="chroot $DTMP qemu-${QEMUARC}-static $(command -v bash) /chrootscript" ; TERMINAL
	else
		check_exit
	fi

elif [ "$CHROOT" = "N" ] ; then

	TT="$TITLE" ; COM="bash /chrootscript" ; TERMINAL

else
	check_exit
fi


if [ "$CHROOT" = "Y" ] ; then
	# Internet cleaning
	rm -f $DTMP/etc/resolv.conf
	mv $DTMP/etc/resolv.conf_ORIG $DTMP/etc/resolv.conf
fi


### REVIEW GRUB POST-CHROOT ########################################

if [ -e "$DTMP/GRUBERROR" ] ; then
	rm -f "$DTMP/GRUBERROR"
	$DIALOG $WICON $WTITLE "$TITLE" $WM    $WTEXT $"ERROR: GRUB installation seems to have failed! " $H $W
fi

if [ "$G" = "N" ] ; then
	if   [ "$(command -v nano)" != "" ] ; then
		EDITOR="nano"
	elif [ "$(command -v mcedit)" != "" ] ; then
		EDITOR="mcedit"
	else
		EDITOR="editor"
	fi
else
	if   [ "$(command -v mousepad)" != "" ] ; then
		EDITOR="mousepad"
	elif [ "$(command -v kwrite)" != "" ] ; then
		EDITOR="kwrite"
	elif [ "$(command -v l3afpad)" != "" ] ; then
		EDITOR="l3afpad"
	elif [ "$(command -v leafpad)" != "" ] ; then
		EDITOR="leafpad"
	elif [ "$(command -v featherpad)" != "" ] ; then
		EDITOR="featherpad"
	elif [ "$(command -v juffed)" != "" ] ; then
		EDITOR="juffed"
	elif [ "$(command -v pluma)" != "" ] ; then
		EDITOR="pluma"
	elif [ "$(command -v gedit)" != "" ] ; then
		EDITOR="gedit"
	elif [ "$(command -v geany)" != "" ] ; then
		EDITOR="geany"
	elif [ "$(command -v kate)" != "" ] ; then
		EDITOR="kate"
	else
		EDITOR="xdg-open"
	fi
fi

if [ -f $DTMP/boot/grub/grub.cfg ] ; then
$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"Do you want to review /boot/grub/grub.cfg ?" $H $W
	if [ "$?" -eq 0 ] ; then
		if [ "$G" = "N" ] ; then
			exec >/dev/tty
		fi
	$EDITOR $DTMP/boot/grub/grub.cfg
		if [ "$G" = "N" ] ; then
			if [ "$DEBUG" != "N" ] ; then
				exec > >(tee -a "$ERRORLOG") 2>&1
			fi
		fi
	fi
elif [ -f $DTMP/boot/grub/menu.lst ] ; then
$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"Do you want to review /boot/grub/menu.lst ?" $H $W
	if [ "$?" -eq 0 ] ; then
		if [ "$G" = "N" ] ; then
			exec >/dev/tty
		fi
	$EDITOR $DTMP/boot/grub/menu.lst
		if [ "$G" = "N" ] ; then
			if [ "$DEBUG" != "N" ] ; then
				exec > >(tee -a "$ERRORLOG") 2>&1
			fi
		fi
	fi
else
	$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"ERROR: GRUB installation failed! " $H $W
fi


### Cleaning ########################################

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

if [ "$CHROOT" = "Y" ] && [ "$CHROOTNATIV" = "N" ] && [ "$(command -v qemu-${QEMUARC}-static)" != "" ] && [ "$QEMUDEL" != "N" ] ; then
	rm -rfv ${DTMP}$(command -v qemu-${QEMUARC}-static)
fi

cp -v --remove-destination $DTMP/chroot.log $HOME/chroot.log
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
	HOMECHROOTLOG=/home/$i/.chroot.log
	mv -f $DTMP/chroot.log $HOMECHROOTLOG
	chown $i:$i $HOMECHROOTLOG
	chmod 600 $HOMECHROOTLOG ; if [ "$(stat -c %U $HOMECHROOTLOG)" != "$i" ] ; then chmod 666 $HOMECHROOTLOG ; fi
	break
fi ; done

rm -f /lsvar /datarecscript /chrootscript /chroot.log $DTMP/lsvar $DTMP/datarecscript $DTMP/chrootscript $DTMP/chroot.log /dtmp/lsvar /dtmp/datarecscript /dtmp/chrootscript /dtmp/chroot.log /tmp/hostarc /tmp/guestarc /tmp/coincidarc $DTMP/update-grub-legacy $DTMP/grub-batch /dtmp/update-grub-legacy /dtmp/grub-batch

umount_chroot () {

### UMOUNT CHROOT ########################################

umount --recursive $DTMP/run && sleep 2
umount --recursive $DTMP/sys && sleep 2
umount --recursive $DTMP/proc && sleep 2
#umount --recursive $DTMP/dev/pts && sleep 2
#sleep 3
umount --recursive $DTMP/dev && sleep 2

umount --recursive $DTMP && sleep 3

umount $DTMP/run
umount $DTMP/sys
umount $DTMP/proc
#umount $DTMP/dev/pts
#sleep 3
umount $DTMP/dev

# unmount additional partitions (as /boot) if they are separated. Externally only if absolute (UUID) names are used.
cat $DTMP/etc/fstab | grep -aEiv "^#" | grep -aEiv ' /media/| / ' | grep -aEi "^UUID=" | while read i ; do
	umount /dev/disk/by-uuid/$(echo "$i" | awk '{print $1}' | sed 's|UUID=||g')
done

sleep 3
umount $OBJSYSPART && sleep 3
lsblk -r -n -o MOUNTPOINT | grep -aE "^$(echo $DTMP | sed "s|/$||g")" | awk '{print length($1)"\t"$1}' | sort -n -r | cut -f 2 | while read i ; do umount "$i" && sleep 3 ; done
cat /etc/mtab | grep -aE " $(echo $DTMP | sed "s|/$||g")" | awk '{print length($2)"\t"$2}' | sort -n -r | cut -f 2 | while read i ; do umount "$i" && sleep 3 ; done
umount --recursive $DTMP && sleep 3
umount $DTMP && sleep 3
if [ "$(find $DTMP -type f)" = "" ] ; then find "$DTMP" -type d  | awk '{print length($1)"\t"$1}' | sort -n -r | cut -f 2 | while read i ; do rmdir "$i" ; done ; fi
rmdir $DTMP
echo "### mtab ##########"
cat /etc/mtab
echo "### findmnt ##########"
findmnt -u -R   # findmnt -l -u -R
echo "### lsblk ##########"
lsblk -o NAME,KNAME,RM,SIZE,RO,TYPE,FSTYPE,MOUNTPOINT,LABEL,UUID
echo "### mountinfo ##########"
cat /proc/self/mountinfo

}

if [ "$CHROOT" = "Y" ] ; then
	umount_chroot
fi

	kill $PIDDIALOGEND 2>/dev/null


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

if [ "$EFIGRUBVERSEL" != "" ] ; then
	EFINOTE=$"\n\nIf when rebooting or turning on the computer, the operating system does not boot, you must enter in the EFI (typically the Del./Supr., Esc., F2 or F12 key at startup) and in Settings, Boot, (BBS) Priority, change the order. Additionally, in some EFI it is necessary to enter in the 'Security' or 'Boot Manager' section and 'Select as EFI file'/'Boot from file' /EFI/picalibre/grubxXX.efi (it is possible that previously in the 'Security' section you must 'Set supervisor password'). To save changes to EFI/BIOS, the key is usually F10."
fi

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

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
