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

# pica-eleva
#
# Upgrade the operating system to a newer version.
#
# 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, diffutils, dpkg, findutils, gawk | mawk | original-awk, grep, kbd, molly-guard | openrc | runit-init | systemd | systemd-sysv | sysvinit-core, sed, sysvinit-utils (<<2.88dsf-59.3) | init-system-helpers, usrmerge
# Recommends: am, consolation | gpm, inetutils-ping | iputils-ping, picanet | network-manager | connman | wicd, pica-skel, wget


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

CNAME="pica-eleva"
PICALIBREVERSION=x
VERSION="1.3.1"
TITLE="Pica-Eleva"
#ICON="/usr/share/icons/pica-eleva.png"

# Translations
if [ "$LANG" = "" ] ; then export $(cat /etc/default/locale | grep -a 'LANG=') ; fi
TEXTDOMAIN=pica-eleva
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=$"Upgrade the operating system to a newer version."
LDESCRIP=$"$TITLE is a tool to upgrade the operating system to a newer version."

# 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=" -x""\t"$"Show help documentation.""\n\n"$"$TITLE will try to ensure that the operating system after upgrading is usable and accessible after reboot (able to boot, with connection to the Internet and also SSH active if it was previously). Therefore, $TITLE should also be able to be used to remotely migrate a virtual server (VPS) that uses any operating system based on Devuan, Debian or derivatives.""\n\n"$"After installing $TITLE, if the operating system uses 'sysvinit' (like PicaLibre and Devuan do), you can reboot, $TITLE will start automatically. You can also manually start $TITLE without rebooting ($TITLE must not be used in a desktop terminal emulator but in a real terminal by simultaneously pressing the Ctrl Alt F1 keys), this is necessary if the operating system does not use 'sysvinit' (but 'systemd' like Debian and some derivatives do by default) or if it is a remote connection (like SSH)."

while getopts x OPTION ; do
	case $OPTION in
		x )   docu_info ; exit 0 ;;
	esac
done

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


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

#DEFAULTDIALOGLIST="yad zenity kdialog"
DEFAULTDIALOGLIST="dialog" ; T="Y" ; G="N"

#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


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

end_script () {
#	if [ -e /etc/rc.local ] ; then
#		sed -i "/.*$CNAME.*/d" /etc/rc.local
#	fi
	apt-get purge -y pica-eleva*
	
	echo $(date +%Y-%m-%d_%H:%M:%S) $"End" >> "$ERRORLOG"
	
#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

# Reboot

if [ "$TS" = "" ] ; then
	TS=10
fi

$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"Do you want to reboot the computer now?" $H $W
if [ "$?" -eq 0 ] ; then
#echo
#echo $"The system will reboot in $TS seconds. To cancel, simultaneously press the Ctrl C keys"
#
#	#for i in $(seq $TS -1 0) ; do sleep 1 ; echo $i | dialog --gauge $"Please wait" 0 50 0 ; done
#	SS=$TS ; while [ $SS -ge 0 ] ; do printf "\r%3s " "$SS" ; sleep 1 ; SS=$(expr $SS - 1) ; done ; printf "\r"

	if [ "$(command -v reboot)" != "" ] ; then
		reboot
			sleep 10
		reboot </dev/null
			sleep 10
		shutdown -r 0
			sleep 10
		shutdown -r 0 </dev/null
			sleep 10
		sync
		reboot -f
	elif [ "$(command -v systemctl)" != "" ] ; then
		systemctl reboot
	elif [ "$(command -v openrc-shutdown)" != "" ] ; then
		openrc-shutdown -r now
	else
		echo "No reboot, no systemctl, no openrc-shutdown"
		exit 1
	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


### INTERNET TEST AND CONFIG ########################################

internet_config () {

INTERNETOPT=$($DIALOG $WICON $WTITLE "$TITLE" $MONOLIST $WTEXT $"No Internet connection.\n\n3 options:" $H $W $LH $COLUMN $COLUMN \
$"1) Leave the upgrade for later (reinstalling $CNAME will be necessary to see the wizard again)." " " \
$"2) Connect now an Internet cable (connect it before continuing)." " " \
$"3) Configure the Internet connection in the terminal." " " \
| head -n 1 )
#"

case $INTERNETOPT in
	
	$"1) Leave the upgrade for later (reinstalling $CNAME will be necessary to see the wizard again)." )
		end_script
	;;
	
	$"2) Connect now an Internet cable (connect it before continuing)." )
		sleep 5
		if [ "$(dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2}' | sed "s|:.*||g" | grep -aEi 'network-manager|connman|wicd' )" = "" ] ; then
			if [ "$(command -v ifconfig)" != "" ] ; then
				DEV=$(ifconfig -a | grep -aE "^[a-z]" | awk '{print $1}' | grep -aEiv avahi | sed 's|: .*||g' | sed 's|:$||g' | grep -aEiv "^lo$" | sort -u | grep -aE "^e" | head -n 1)
				ifconfig $DEV up
			elif [ "$(command -v ip)" != "" ] ; then
				DEV=$(ip a | grep -aE "^[0-9]" | awk '{print $2}' | grep -aEiv avahi | sed 's|: .*||g' | sed 's|:$||g' | grep -aEiv "^lo$" | sort -u | grep -aE "^e" | head -n 1)
				ip link set $DEV up
			else
				echo $"ERROR"
			fi
			if [ "$(command -v dhclient)" != "" ] ; then
				dhclient $DEV
			elif [ "$(command -v dhcpcd)" != "" ] ; then
				dhcpcd $DEV
			elif [ "$(command -v udhcpc)" != "" ] ; then
				udhcpc -i $DEV
			else
				echo $"ERROR" DHCP
			fi
		fi
	;;
	
	$"3) Configure the Internet connection in the terminal." )
		#NMOPT="picanet wicd-curses nmtui ceni"
		NMOPT="picanet wicd-curses nmtui"
		if [ "$(command -v $NMOPT)" != "" ] ; then
			exec >/dev/tty
			for i in $NMOPT ; do
				if [ "$(command -v $i )" != "" ] ; then $i ; break ; fi
			done
			if [ "$DEBUG" != "N" ] ; then
				exec > >(tee -a "$ERRORLOG") 2>&1
			fi
		else
			$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"There is no application in the system to configure the Internet connection in the terminal." $H $W
			internet_config
		fi
	;;
	
	* )
		true
	;;
	
esac

}


internet_test () {

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

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

}


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

if [ "$MIGRA" = "" ] ; then
if [ ! -e /etc/picalibre_version ] ; then
	MIGRA="Y"
fi
fi

# Ensure that if a problem occurs and pica-eleva fails to finish (end_script is not reached), pica-eleva does not run on each boot!
if [ -e /etc/rc.local ] ; then
	sed -i "/.*$CNAME.*/d" /etc/rc.local
fi

tty >> "$ERRORLOG"

for i in cdm console-tdm edm entrance gdm gdm3 kdm lightdm lxdm ly mdm nodm qingy sddm slim tdm wdm xdm ; do
	#if [ "$(command -v systemctl)" != "" ] ; then if [ "$(systemctl show $i | grep -a '=active')" != "" ] ; then systemctl stop $i.service ;
	if [ "$(command -v service)" != "" ] ; then
		if [ "$(service $i status 2>/dev/null | grep -aEv ' not | inactive | off ')" != "" ] ; then service $i stop ; fi
	elif [ -e "/etc/init.d/$i" ] ; then
		/etc/init.d/$i stop
	elif [ "$(command -v $i)" != "" ] ; then
		# https://manpages.debian.org/signal.7#Signal_numbering_for_standard_signals
		pkill -15 ^$i$
		sleep 1
		pkill -9 ^$i$
	else
		true
	fi
done

chvt 1

tty >> "$ERRORLOG"

#t0=$(date +"%s"); wget http://www.gnu.org/doc/fsfs3-hardcover.pdf -O /dev/null ; t1=$(date +"%s") ; echo $t0 $t1 ; DS=$(echo "1.5 / ($t1 - $t0)" | bc -l) ; TS=$(echo "c=( 2 * 2000 / $DS / 60 ) + 0.5 ; scale=0 ; c/1" | bc -l) ; echo $TS min

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 )
POSTDEBIANVERSION=$(expr $DEBIANVERSION + 1)

if [ "$DEBIANVERSION" -gt 0 ] && [ "$PICALIBREVERSION" != "x" ] ; then
	if [ "$PICALIBREVERSION" != "$POSTDEBIANVERSION" ] ; then
		$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"It seems that the version of your operating system is $DEBIANVERSION\n\nIf so, then you should first upgrade to $POSTDEBIANVERSION and no $PICALIBREVERSION\n\nDo you want to continue?" $H $W
		if [ "$?" -ne 0 ] ; then
			end_script
		fi
	fi
fi

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

#service mariadb stop
# =
#/etc/init.d/mariadb stop
# &&
#tail /var/log/syslog | grep -a "Shutdown complete"

$DIALOG $WICON $WTITLE "$TITLE" $QYN   $WTEXT $"The operating system will be upgraded to a newer version.\n\nPlease ensure you choose the PicaLibre version ($PICALIBREVERSION) you want! \n\nUpgrading the operating system will take several hours (and the process must not be interrupted).\n\nIf it is a laptop, you probably want to use it plugged into the power supply.\n\nIf it is a server, before continuing you must make a clean stop of active databases (and perhaps also other services or daemons).\n\nDo you want to continue?" $H $W

if [ "$?" -eq 0 ] ; then
	
	df -h | tee -a "$ERRORLOG"
	
	LOCALREPO=$(cat /etc/apt/sources.list | grep -aEi "^deb " | grep -aEiv '//' )
	
	internet_test
	if [ "$TESTINTERNET" = "N" ] ; then
		internet_config
		internet_test
	fi
	
	if [ "$TESTINTERNET" = "N" ] && [ "$LOCALREPO" = "" ] ; then
		echo $"ERROR: No Internet connection, no local copy of packages."
		$DIALOG $WICON $WTITLE "$TITLE" $ERROR $WTEXT $"ERROR: No Internet connection, no local copy of packages." $H $W
		end_script
	fi
	
	if [ "$(command -v apt-actualiza)" != "" ] ; then
		apt-actualiza
	else
		apt-get update -y
		apt-get upgrade -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold"
		apt-get dist-upgrade -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold"
	fi

	DATECOP=$(date +%Y%m%d%H%M%S)
	mv /etc/apt/sources.list /etc/apt/sources.list_COP-$DATECOP
	if [ "$(ls /etc/apt/sources.list.d/)" != "" ] ; then mkdir /etc/apt/sources.list.d_COP-$DATECOP ; mv /etc/apt/sources.list.d/* /etc/apt/sources.list.d_COP-$DATECOP/ ; fi
	cp -av /usr/share/$CNAME/repo/* /etc/apt/sources.list

df -h | tee -a "$ERRORLOG"
	find "$TFS"/var/lib/apt/lists -type f | grep -aEiv "lock$" | while read i ; do rm -f "$i" ; done
	if [ -e "$TFS/var/cache/apt-xapian-index/" ] ; then find "$TFS"/var/cache/apt-xapian-index/ -type f | while read i ; do rm -rf $i ; done ; fi
	find "$TFS"/var/cache/apt/  -maxdepth 1 -type f | grep -aEi "pkgcache|srcpkgcache" | while read i ; do rm -rf $i ; done

	apt-get --allow-releaseinfo-change update -y
	apt-get update -y
	if [ "$?" -ne 0 ] && [ "$MIGRA" = "Y" ] ; then apt-get --allow-releaseinfo-change update --allow-insecure-repositories -y ; fi
	
	df -h | tee -a "$ERRORLOG"
	
	dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2"\t"$3}' > /tmp/dpkg_prev.txt
	echo '============/tmp/dpkg_prev.txt' >> "$ERRORLOG"
	cat /tmp/dpkg_prev.txt                >> "$ERRORLOG"
	echo '==============================' >> "$ERRORLOG"
	
	if [ "$MIGRA" = "Y" ] ; then
		find /etc/ -type f | grep -ai network | while read i ; do
			echo '=========='"$i" >> "$ERRORLOG"
			cat "$i"              >> "$ERRORLOG"
		done
		echo '=============================='
	fi
	
	# Keyring Devuan:
	apt-get install --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" devuan-keyring
	if [ "$?" -ne 0 ] ; then apt-get install --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" devuan-keyring ; fi
	if [ "$?" -ne 0 ] && [ "$MIGRA" = "Y" ] ; then apt-get install --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" --allow-unauthenticated devuan-keyring ; fi
	if [ "$?" -ne 0 ] ; then
	cd /var/cache/apt/archives/
	wget https://pkgmaster.devuan.org/devuan/pool/main/d/devuan-keyring/devuan-keyring_2025.08.09_all.deb
	if [ "$?" -ne 0 ] ; then
		wget https://ftp.fau.de/devuan/devuan/pool/main/d/devuan-keyring/devuan-keyring_2025.08.09_all.deb
		if [ "$?" -ne 0 ] ; then
			wget https://mirrors.dotsrc.org/devuan/devuan/pool/main/d/devuan-keyring/devuan-keyring_2025.08.09_all.deb
			if [ "$?" -ne 0 ] ; then
				end_script
			fi
		fi
	fi
	dpkg -i devuan-keyring_2025.08.09_all.deb
	rm -f devuan-keyring_2025.08.09_all.deb
	cd - 1>/dev/null
	# gpg --keyserver pgpkeys.eu --recv-key 541922FB
	##gpg --keyserver keyserver.ubuntu.com --recv-key 541922FB
	# gpg --export --armor 541922FB | apt-key add -   #  apt-key is deprecated
	fi

	# Keyring Pica:
	apt-get install --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" pica-keyring
	if [ "$?" -ne 0 ] ; then apt-get install --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" pica-keyring ; fi
	if [ "$?" -ne 0 ] && [ "$MIGRA" = "Y" ] ; then apt-get install --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" --allow-unauthenticated pica-keyring ; fi
	if [ "$?" -ne 0 ] ; then
	cd /var/cache/apt/archives/
	wget https://deb.picalibre.org/pool/main/gen/p/pica-keyring/pica-keyring_1.0.0_all.deb
	if [ "$?" -ne 0 ] ; then
		wget https://deb2.picalibre.org/pool/main/gen/p/pica-keyring/pica-keyring_1.0.0_all.deb
		if [ "$?" -ne 0 ] ; then
			end_script
		fi
	fi
	dpkg -i pica-keyring_1.0.0_all.deb
	rm -f pica-keyring_1.0.0_all.deb
	cd - 1>/dev/null
	# gpg --keyserver pgpkeys.eu --recv-key 5B8647E8
	##gpg --keyserver keyserver.ubuntu.com --recv-key 5B8647E8
	# gpg --export --armor 5B8647E8 | apt-key add -   #  apt-key is deprecated
	fi

	# Keyring Trinity:
	apt-get install --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" trinity-keyring
	if [ "$?" -ne 0 ] ; then apt-get install --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" trinity-keyring ; fi
	if [ "$?" -ne 0 ] && [ "$MIGRA" = "Y" ] ; then apt-get install --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" --allow-unauthenticated trinity-keyring ; fi
	if [ "$?" -ne 0 ] ; then
	cd /var/cache/apt/archives/
	wget https://mirrorservice.org/sites/trinitydesktop.org/trinity/deb/trinity-keyring.deb
	if [ "$?" -ne 0 ] ; then
		wget https://ftp.fau.de/trinity/deb/trinity-keyring.deb
		if [ "$?" -ne 0 ] ; then
			end_script
		fi
	fi
	dpkg -i trinity-keyring.deb
	rm -f trinity-keyring.deb
	cd - 1>/dev/null
	# gpg --keyserver pgpkeys.eu --recv-key c93af1698685ad8b
	##gpg --keyserver keyserver.ubuntu.com --recv-key c93af1698685ad8b
	# gpg --export --armor c93af1698685ad8b | apt-key add -   #  apt-key is deprecated
	fi

	#echo " "
	#echo $"During the upgrade, there will be a moment when information about the news will be displayed for your reading. To exit the 'read news' mode, press the 'Q' key."
	#read -t 20 SEL
	#echo " "
	# Dpkg::Options::="--force-confold" => upstream conf-file as .dpkg-dist
	# Dpkg::Options::="--force-confnew" => previous conf-file as .dpkg-old
	for i in /home/* ; do if [ -e "$i/.mozilla" ] ; then cp -av --remove-destination $i/.mozilla $i/.mozilla_pica-eleva ; fi ; done
	for i in /home/* ; do if [ -e "$i/.config/firefox" ] ; then cp -av --remove-destination $i/.config/firefox $i/.config/firefox_pica-eleva ; fi ; done
	for i in /home/* ; do if [ -e "$i/.local/share/firefox" ] ; then cp -av --remove-destination $i/.local/share/firefox $i/.local/share/firefox_pica-eleva ; fi ; done
	apt-get clean
df -h | tee -a "$ERRORLOG"
	if [ -e "/etc/grubil" ] ; then cat "/etc/grubil" ; sleep 10 ; fi
	export DEBIAN_FRONTEND=noninteractive
	export APT_LISTCHANGES_FRONTEND=cat
	apt-get --allow-releaseinfo-change update -y
	apt-get update -y
df -h | tee -a "$ERRORLOG"
	apt-get install --no-install-recommends -y -o APT::Keep-Downloaded-Packages="false" -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold" $(echo $(dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2}' | grep -aEi "^fonts-|^ttf-|^unifont$"))
df -h | tee -a "$ERRORLOG"
	apt-get upgrade -y -o APT::Keep-Downloaded-Packages="false" -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold"
df -h | tee -a "$ERRORLOG"
	apt-get dist-upgrade -y -o APT::Keep-Downloaded-Packages="false" -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold"
df -h | tee -a "$ERRORLOG"
	export DEBIAN_FRONTEND=dialog ; apt-get dist-upgrade -y -o APT::Keep-Downloaded-Packages="false" -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold" ; export DEBIAN_FRONTEND=noninteractive
df -h | tee -a "$ERRORLOG"
	if [ "$(command -v postinst)" != "" ] ; then postinst ; fi
	
	for i in $(dpkg -l | awk '{print $2}' | sed "s|:.*||g" | grep -aEi "^picalibre" | sort -V) ; do apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" "$i" ; done
	for i in $(dpkg -l | awk '{print $2}' | sed "s|:.*||g" | grep -aEi "^linux-libre" | sort -V) ; do apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" "$i" ; done
	for i in $(dpkg -l | awk '{print $2}' | sed "s|:.*||g" | grep -aEi "^linux-image" | sort -V) ; do apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confnew" "$i" ; done
	
	if [ -e /etc/debian_version ] && [ -e /usr/share/$CNAME/version/debian_version ] ; then rm -f /etc/debian_version ; fi
	if [ -e /etc/devuan_version ] && [ -e /usr/share/$CNAME/version/devuan_version ] ; then rm -f /etc/devuan_version ; fi
	if [ -e /etc/picalibre_version ] && [ -e /usr/share/$CNAME/version/picalibre_version ] ; then rm -f /etc/picalibre_version ; fi
	cp -av /usr/share/$CNAME/version/* /etc/
	
	if [ "$MIGRA" = "Y" ] ; then
		
		apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold" anacron apt at base-files base-passwd bash bash-completion bootlogd bsdutils busybox-static bzip2 ca-certificates chrony console-setup console-setup-linux coreutils cron opensysusers dash debian-security-support debianutils dhcpcd-base dialog diffutils dpkg findutils firmware-linux-free gawk gettext gnupg pinentry-tty grep gzip hostname ifupdown initramfs-tools init-system-helpers iproute2 iputils-ping iw less libc-bin linux-sysctl-defaults login lsb-release lsof mount nano ncurses-base ncurses-bin netbase orphan-sysvinit-scripts passwd perl-base procps rfkill rsyslog sed sysvinit-core sysvinit-utils sysv-rc tar tzdata util-linux wget wpasupplicant xkb-data xz-utils
		
		apt-get purge -y ^systemd
		apt-get purge -y ^networkd
		
		rm -rf /etc/resolv.conf
		echo nameserver 185.222.222.222 > /etc/resolv.conf
		echo nameserver 91.239.100.100 >> /etc/resolv.conf
		
		# --reinstall with --allow-downgrades
		LANG=C apt list 2>>$ERRORLOG | grep -a local]$ | grep -aEiv "$(uname -r)" | grep -aEiv 'keyring|libdvdcss' | awk -F ' |\t|/' '{print $1}' | while read i ; do apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold" --allow-downgrades $i ; done
		LANG=C apt list 2>>$ERRORLOG | grep -a local]$ | grep -aEiv "$(uname -r)" | grep -aEiv 'keyring|libdvdcss' | awk -F ' |\t|/' '{print $1}' | while read i ; do apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold" --allow-downgrades $i=$(apt-cache madison $i | sed 's| ||g' | cut -d '|' -f 2 | sort -V | tail -n 1) ; done
		
		apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold" anacron apt at base-files base-passwd bash bash-completion bootlogd bsdutils busybox-static bzip2 ca-certificates chrony console-setup console-setup-linux coreutils cron opensysusers dash debian-security-support debianutils dhcpcd-base dialog diffutils dpkg findutils firmware-linux-free gawk gettext gnupg pinentry-tty grep gzip hostname ifupdown initramfs-tools init-system-helpers iproute2 iputils-ping iw less libc-bin linux-sysctl-defaults login lsb-release lsof mount nano ncurses-base ncurses-bin netbase orphan-sysvinit-scripts passwd perl-base procps rfkill rsyslog sed sysvinit-core sysvinit-utils sysv-rc tar tzdata util-linux wget wpasupplicant xkb-data xz-utils
		
	fi
	
	dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2"\t"$3}' > /tmp/dpkg_post.txt
	echo '============/tmp/dpkg_post.txt' >> "$ERRORLOG"
	cat /tmp/dpkg_post.txt                >> "$ERRORLOG"
	echo '==============================' >> "$ERRORLOG"
	
	diff <(cat /tmp/dpkg_prev.txt | awk '{print $1}') <(cat /tmp/dpkg_post.txt | awk '{print $1}') | grep -aEi "^<|^>"
	
	if [ "$(command -v apt)" != "" ] ; then
		ESP=$(printf '\302\240')
#		if [ "$PRE" = "FALSE" ] ; then PRE="TRUE" ; fi
#		if [ "$POST" = "off" ] ; then POST="on" ; fi
		OBS=$(LANG=C apt list 2>>$ERRORLOG | grep -a local]$ | grep -aEiv "$(uname -r)" | grep -aEiv 'keyring|libdvdcss' | awk -F ' |\t|/' '{print "'"$PRES"'",$1" ","'"$ESP"'","'"$POSTS"'"}')
	fi
	if [ "$OBS" != "" ] ; then
		SELOBS=$($DIALOG $WICON $WTITLE "$TITLE" $MULTIPLELIST $WTEXT $"The following packages appear to be old packages possibly unnecessary and if so recommended for deletion (old dependencies or abandoned packages). Note that if you installed packages that are not part of PicaLibre, they could be listed here. If you select 'Yes/OK' they will be deleted, you can uncheck those you want to keep, or select 'No/Cancel' to keep them all. If in doubt, select 'No/Cancel'." $H $W $LH $COLUMN $COLUMN $COLUMN $OBS | sed "s|$ESP||g" | sed 's|^TRUE||g')
		if [ "$SELOBS" != "" ] ; then
			apt-get purge -y $(echo $SELOBS)
		fi
	fi

	if [ "$MIGRA" = "Y" ] ; then
		
		apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold" anacron apt at base-files base-passwd bash bash-completion bootlogd bsdutils busybox-static bzip2 ca-certificates chrony console-setup console-setup-linux coreutils cron opensysusers dash debian-security-support debianutils dhcpcd-base dialog diffutils dpkg findutils firmware-linux-free gawk gettext gnupg pinentry-tty grep gzip hostname ifupdown initramfs-tools init-system-helpers iproute2 iputils-ping iw less libc-bin linux-sysctl-defaults login lsb-release lsof mount nano ncurses-base ncurses-bin netbase orphan-sysvinit-scripts passwd perl-base procps rfkill rsyslog sed sysvinit-core sysvinit-utils sysv-rc tar tzdata util-linux wget wpasupplicant xkb-data xz-utils
		
		for i in dropbear openssh-client openssh-server tinysshd ssh ; do
			if [ "$(cat /tmp/dpkg_prev.txt | grep -aEi ^$i)" != "" ] && [ "$(dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2}' | sed "s|:.*||g" | grep -aEi ^$i$ )" = "" ] ; then
				apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold" $i
			fi
		done
		
		dpkg -l | grep -aEiv "^ii|^hi"
		
	fi

	apt-get install --reinstall --no-install-recommends -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold" pica-apt picainfo pica-ip pica-keyring pica-skel
	if [ "$(command -v reconfig)" != "" ] ; then reconfig ; fi
	if [ "$(command -v postinst)" != "" ] ; then postinst ; fi
	
	dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2"\t"$3}' > /tmp/dpkg_final.txt
	echo '============/tmp/dpkg_final.txt' >> "$ERRORLOG"
	cat /tmp/dpkg_final.txt                >> "$ERRORLOG"
	echo '=============================='  >> "$ERRORLOG"
	
	diff <(cat /tmp/dpkg_prev.txt | awk '{print $1}') <(cat /tmp/dpkg_final.txt | awk '{print $1}') | grep -aEi "^<|^>"

	dpkg -l | grep -aEiv "^ii|^hi" > /tmp/dpkg_problem.txt
	echo '============/tmp/dpkg_problem.txt' >> "$ERRORLOG"
	cat /tmp/dpkg_problem.txt                >> "$ERRORLOG"
	echo '=============================='    >> "$ERRORLOG"
	
	apt-get clean
df -h | tee -a "$ERRORLOG"

if [ "$(cat /etc/network/interfaces | grep -aEiv ^# | grep -aEi iface | grep -aEi inet)" = "" ] && [ "$(ls /etc/network/interfaces.d/)" = "" ] && [ "$(dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2}' | sed "s|:.*||g" | grep -aEi network-manager )" = "" ] ; then
cat > /etc/network/interfaces <<EOF
# This file describes the network interfaces available on your system
# and how to activate them. For more information, read interfaces(5).

auto lo
iface lo inet loopback

auto /e*=e
iface e inet dhcp

EOF
fi
	
	if [ "$(command -v am)" != "" ] ; then
		am &
	fi

	$DIALOG $WICON $WTITLE "$TITLE" $INFO  $WTEXT $"$TITLE finished." $H $W
	
	TS=60

	end_script

else

	end_script

fi

exit 0
