#!/bin/bash
#
# Copyright (c) Authors: https://www.armbian.com/authors
#
# This file is licensed under the terms of the GNU General Public
# License version 2. This program is licensed "as is" without any
# warranty of any kind, whether express or implied.

# read distribution status
# shellcheck source=/dev/null
[[ -f /etc/lsb-release ]] && . /etc/lsb-release
[[ -f /etc/os-release ]] && . /etc/os-release
[[ -z "$DISTRIB_CODENAME" ]] && DISTRIB_CODENAME="${VERSION_CODENAME}"
[[ -n "$DISTRIB_CODENAME" && -f /etc/armbian-distribution-status ]] && DISTRIBUTION_STATUS=$(grep "^$DISTRIB_CODENAME" /etc/armbian-distribution-status | cut -d"=" -f2 | cut -d";" -f1)

. /etc/armbian-release
. /usr/lib/armbian/armbian-common

# Cleanup gate: EXIT trap removes the marker only after FIRSTLOGIN_SUCCESS=1,
# so power-loss or mid-run failure reruns firstlogin on next boot.
FIRSTLOGIN_SUCCESS=0
_firstlogin_cleanup() {
	if [ "$FIRSTLOGIN_SUCCESS" = "1" ]; then
		rm -f /root/.not_logged_in_yet
		sync -f /root 2>/dev/null || sync
	fi
}
trap _firstlogin_cleanup EXIT
# DM takeover (gdm/lightdm) sends SIGHUP to the console's foreground process
# while bash is mid-command. An untrapped SIGHUP kills bash mid-flight and its
# EXIT trap gets cut short: builtins still run, but external commands (rm) do
# not survive the dying shell. Handle the signal in normal execution context
# instead — cleanup runs fully, then exit.
trap '_firstlogin_cleanup; exit' HUP INT TERM

# armbian-firstrun-gui images defer the root filesystem resize until the first login is done.
# Run it before the reboot checks that follow. PRESET_DEFER_ROOTFS_RESIZE=1: the wizard can
# still copy the small system to another drive, it starts the resize itself:
#   rm -f /root/.defer_rootfs_resize; systemctl restart armbian-resize-filesystem
# Without that, the next boot resizes (no first login is pending then).
release_rootfs_resize() {
	[[ -f /root/.defer_rootfs_resize ]] || return 0
	[[ "${PRESET_DEFER_ROOTFS_RESIZE}" == 1 ]] && return 0
	rm -f /root/.defer_rootfs_resize
	# Wait for it: the reboot check below reads /var/run/resize2fs-reboot.
	echo -e "\nResizing the root filesystem. On a large drive this takes some minutes.\n"
	systemctl restart armbian-resize-filesystem || true
}

# PRESET_DEFER_ROOTFS_RESIZE=1: the wizard still shows its install page after the setup.
# A display manager takes the screen from it. The units in this file start when the
# wizard ends: armbian-firstrun-gui.service (ExecStopPost) or start_desktop_later below.
DESKTOP_START_FILE=/run/armbian-firstrun-gui.start-later

# Start the desktop units now, or after the wizard.
start_desktop() {
	if [[ "${PRESET_DEFER_ROOTFS_RESIZE}" == 1 ]]; then
		printf '%s\n' "$@" >> "${DESKTOP_START_FILE}"
		return 0
	fi
	ignore_logout_stop
	systemctl --no-block start "$@" 2> /dev/null
}

# A display manager stops getty@tty1 and with it this login. systemctl can still run then:
# its end by SIGTERM or SIGHUP prints "Terminated" or "Hangup" on the console.
# This script ends the login itself.
ignore_logout_stop() {
	trap '' TERM HUP
}

# A display manager takes the screen: end the root login on tty1. Only on tty1 itself:
# the wizard runs this script on a pseudo terminal and reads exit code 1 as a failure.
logout_console() {
	[[ "$(tty)" == /dev/tty1 ]] && who -la | grep root | grep -q tty1 && exit 1
}

# The wizard ended: start the units that start_desktop kept.
start_desktop_later() {
	[[ -f "${DESKTOP_START_FILE}" ]] || return 0
	ignore_logout_stop
	xargs -r systemctl --no-block start < "${DESKTOP_START_FILE}" 2> /dev/null
	rm -f "${DESKTOP_START_FILE}"
}

check_abort() {

	echo -e "\nDisabling user account creation procedure\n"
	FIRSTLOGIN_SUCCESS=1
	release_rootfs_resize
	if [[ ${USER_SHELL} == zsh ]]; then
		printf "\nYou selected \e[0;91mZSH\x1B[0m as your default shell. If you want to use it right away, please logout and login! \n\n"
	fi
	trap - INT
	exit 0

}

mask2cidr() {
	nbits=0
	IFS=.
	for dec in $1 ; do
		case $dec in
			255) let nbits+=8;;
			254) let nbits+=7;;
			252) let nbits+=6;;
			248) let nbits+=5;;
			240) let nbits+=4;;
			224) let nbits+=3;;
			192) let nbits+=2;;
			128) let nbits+=1;;
			0);;
			*) echo "Error: $dec is not recognised"; exit 1
		esac
	done
	echo "$nbits"
}

createYAML() {
   local YAML="network:\n"
    YAML+="  $DEVTYPE:\n"
    YAML+="    $DEVICE_NAME:\n"
	if [[ "${PRESET_NET_USE_STATIC}" == 1 ]]; then
		YAML+="      addresses:\n"
		YAML+="        - $PRESET_NET_STATIC_IP/$PRESET_NET_STATIC_MASK\n"
		if [[ -n "${PRESET_NET_STATIC_GATEWAY}" ]]; then   YAML+="      routes:\n";fi
		if [[ -n "${PRESET_NET_STATIC_GATEWAY}" ]]; then   YAML+="        - to: default\n";fi
		if [[ -n "${PRESET_NET_STATIC_GATEWAY}" ]]; then   YAML+="          via: ${PRESET_NET_STATIC_GATEWAY}\n";fi
		if [[ -n "${PRESET_NET_STATIC_DNS}" ]]; then       YAML+="      nameservers:\n"; fi
		if [[ -n "${PRESET_NET_STATIC_DNS}" ]]; then       YAML+="        addresses: [$PRESET_NET_STATIC_DNS]\n"; fi
	else
		YAML+="      dhcp4: yes\n"
		YAML+="      dhcp6: yes\n"
	fi
	if [[ "${PRESET_NET_WIFI_ENABLED}" == 1 ]]; then
		if [[ -n "${PRESET_NET_WIFI_COUNTRYCODE}" ]]; then YAML+="      regulatory-domain: $PRESET_NET_WIFI_COUNTRYCODE\n"; fi
		if [[ -n "${PRESET_NET_WIFI_SSID}" ]]; then        YAML+="      access-points:\n"; fi
		if [[ -n "${PRESET_NET_WIFI_SSID}" ]]; then        YAML+="        \"$PRESET_NET_WIFI_SSID\":\n"; fi
		if [[ -n "${PRESET_NET_WIFI_KEY}" ]]; then
			YAML+="          password: |-\n"
			YAML+="            $PRESET_NET_WIFI_KEY\n"
		fi
	fi
	printf "%s" "$YAML"
}

do_firstrun_automated_network_configuration()
{
	#-----------------------------------------------------------------------------
	#Config FP
	local fp_config='/root/.not_logged_in_yet'

	#-----------------------------------------------------------------------------
	#Grab user requested settings
	if [[ -f $fp_config ]]; then

		# Convert line endings to Unix from Dos
		sed -i $'s/\r$//' "$fp_config"

		# check syntax
		bash -n "$fp_config" || return

		# Load vars directly from file
		source "$fp_config"

		# Obtain backward configuration compatibility
		# DNS may be separated by spaces, commas or both ("8.8.8.8, 1.1.1.1", as
		# Armbian Imager suggests); netplan needs a plain comma list, an empty
		# element ("8.8.8.8,,1.1.1.1") is invalid YAML and breaks the network.
		PRESET_NET_STATIC_DNS=$(tr -s ', ' ',' <<< "${PRESET_NET_STATIC_DNS}" | sed 's/^,//; s/,$//')
		PRESET_NET_STATIC_MASK=$(mask2cidr $PRESET_NET_STATIC_MASK)

		#-----------------------------------------------------------------------------
		# Set Network
		if [[ $PRESET_NET_CHANGE_DEFAULTS == 1 ]]; then

			# - Get name of 1st available ethernet and wifi adapter
			eth_index="$(ip link | awk -F: '$0 !~ "lo|vir|wl|^[^0-9]"{print $2;getline}' | sed 's/^[ \t]*//' | grep "^e" | head -1)"
			wlan_index="$(iw dev | awk '$1=="Interface"{print $2}' | head -n 1)"

			local CONFIG_NAME="-dhcp"
			# for static IP we only append settings
			if [[ $PRESET_NET_USE_STATIC == 1 ]]; then
				local CONFIG_NAME="-static"
			fi

			# at least one device has to exits
			if [[ -n $eth_index || -n $wlan_index ]]; then

				# - Wifi enable
				if [[ $PRESET_NET_WIFI_ENABLED == 1 ]]; then

						DEVICE_NAME=${wlan_index}
						DEVTYPE=wifis
						local _f="/etc/netplan/30-${DEVTYPE}${CONFIG_NAME}.yaml"
						if echo -e "$(createYAML)" > "${_f}.tmp"; then
							atomic_write "${_f}.tmp" "${_f}" 600 || return 1
						else
							rm -f "${_f}.tmp"
							return 1
						fi
						PRESET_NET_ETHERNET_ENABLED=0
						netplan apply > /dev/null 2>&1

				# - Ethernet enable
				elif [[ $PRESET_NET_ETHERNET_ENABLED == 1 ]]; then

						# remove dhcp config
						rm -f /etc/netplan/10-dhcp-all-interfaces.yaml

						DEVICE_NAME=${eth_index}
						DEVTYPE=ethernets
						local _f="/etc/netplan/30-${DEVTYPE}${CONFIG_NAME}.yaml"
						if echo -e "$(createYAML)" > "${_f}.tmp"; then
							atomic_write "${_f}.tmp" "${_f}" 600 || return 1
						else
							rm -f "${_f}.tmp"
							return 1
						fi
						PRESET_NET_WIFI_ENABLED=0
						netplan apply > /dev/null 2>&1
				fi

			fi
		fi
	fi
} #do_firstrun_automated_network_configuration

# Try to retrieve the local IP address to display
get_local_ip_addr() {
	# How many seconds to wait at maximum to find out the local IP address
	local ip_wait_seconds_counter=6
	local local_device_ip=""
	local retry_message=""

	while [[ -z "$local_device_ip" ]] && [ ${ip_wait_seconds_counter} -ge 0 ]; do
		local_device_ip=$(ip -4 addr show scope global | grep inet | awk '{print $2}' | cut -d/ -f1 | awk '{$1=$1}1' FS='\n' OFS=',' RS=)

		# Set retry message if some retries are left, but no IP address has been found yet
		if [[ -z "$local_device_ip" ]] && [[ $ip_wait_seconds_counter -gt 0 ]]; then
			retry_message="\e[1m\e[97mWaiting for local connection!\x1B[0m Retrying... (${ip_wait_seconds_counter})"
		# Empty retry message if IP address has been found
		elif [[ -n "$local_device_ip" ]]; then
			retry_message=""
		# Set timeout message if no retries are left and no IP address has been found
		else
			retry_message="\e[1m\e[31mNetwork connection timeout!\x1B[0m"
		fi

		# Display the message
		echo -e "\e[1A\e[KIP address: \x1B[92m${local_device_ip}\x1B[0m ${retry_message}"

		# Wait for 1 second if the IP has not yet been found
		if [[ -z "$local_device_ip" ]]; then
			sleep 1
		fi

		ip_wait_seconds_counter=$((ip_wait_seconds_counter - 1))
	done
}

read_password() {

	unset password
	unset charcount
	prompt="$1 password: "

	stty -echo

	charcount=0
	while IFS= read -p "$prompt" -r -s -n 1 char; do
		if [[ $char == $'\0' ]]; then
			break
		fi

		# Handle backspace
		if [[ $char == $'\177' ]]; then
			if [ $charcount -gt 0 ]; then
				charcount=$((charcount - 1))
				prompt=$'\b \b'
				password="${password%?}"
			else
				prompt=''
			fi
		else
			charcount=$((charcount + 1))
			prompt='*'
			password+="$char"
		fi
	done

	stty echo

}

set_shell() {

	readarray -t optionsAudits <<< "$(grep "zsh\|/bash" /etc/shells | sed 's/\/bin\///g' | sed 's/\/usr//g' | uniq)"
	USER_SHELL="bash"

	if [[ "${#optionsAudits[@]}" -gt 1 ]]; then
		while :; do
			while [[ ! "${reply}" =~ ^(1|2)$ ]]; do
				i=1
				echo -e "\nChoose default system command shell:\n"
				for o in "${optionsAudits[@]}"; do
					echo "$i) $o"
					((i++)) || true
				done
				if [[ -z $PRESET_USER_SHELL && $preset_unattended != 1 ]]; then
					read -r reply
				else
					reply=1
					for index in "${!optionsAudits[@]}"; do
						if [[ "${optionsAudits[$index]}" == "$PRESET_USER_SHELL" ]]; then
							reply=$(($index + 1))
							break
						fi
					done
				fi
			done
			case $reply in
				"1" | "${optionsAudits[0]}")
					USER_SHELL="${optionsAudits[0]}"
					break
					;;
				"2" | "${optionsAudits[1]}")
					USER_SHELL="${optionsAudits[1]}"
					break
					;;
				*)
					USER_SHELL="${optionsAudits[0]}"
					break
					;;
			esac
		done
	# Display shell selection only if needs to be selected
	echo -e "\nShell: \x1B[92m${USER_SHELL^^}\x1B[0m"
	fi

	SHELL_PATH=$(grep "/$USER_SHELL$" /etc/shells | tail -1)
	chsh -s "$(grep -iF "/$USER_SHELL" /etc/shells | tail -1)"

	# Change shell for future users. useradd reads /etc/default/useradd;
	# /etc/adduser.conf is optional, so guard that edit.
	local _f="/etc/default/useradd"
	if sed "s|^SHELL=.*|SHELL=${SHELL_PATH}|" "${_f}" > "${_f}.tmp"; then
		atomic_write "${_f}.tmp" "${_f}" || return 1
	else
		rm -f "${_f}.tmp"
		return 1
	fi
	if [[ -f /etc/adduser.conf ]]; then
		_f="/etc/adduser.conf"
		if sed "s|^DSHELL=.*|DSHELL=${SHELL_PATH}|" "${_f}" > "${_f}.tmp"; then
			atomic_write "${_f}.tmp" "${_f}" || return 1
		else
			rm -f "${_f}.tmp"
			return 1
		fi
	fi

}

# List locales for a country code (all locales when empty). Prefer UTF-8.
find_locales() {
	local list
	list=$(grep territory /usr/share/i18n/locales/* | grep _"$1" | cut -d ":" -f 1 | cut -d "/" -f 6 |
		xargs -I{} grep {} /usr/share/i18n/SUPPORTED)
	{ grep "UTF-8$" <<< "${list}" || echo "${list}"; } | cut -d " " -f 1
}

# Print "timezone|country code" for this machine. Try the next service when one
# fails or is rate limited. Print nothing when all fail.
# At first login, DNS or the network can still be starting: retry all services 3 times.
# The clock can be wrong before NTP sync, then TLS fails: ip-api.com uses plain HTTP.
# Cloudflare at 1.1.1.1 needs no DNS. It gives the country only; the timezone comes
# from zone.tab when the country has one zone. -k: a wrong clock must not break it.
# Failures go to the journal: journalctl -t armbian-firstlogin
geolocate() {
	local round url filter json rc tz cc dns_failed
	local -a opts
	echo -e "\nDetecting location ..." >&2
	for round in 1 2 3; do
		# a dead resolver makes each curl wait for its timeout: test DNS once per round
		dns_failed=0
		timeout 4 getent hosts ipinfo.io > /dev/null 2>&1 || dns_failed=1
		while IFS=' ' read -r url filter; do
			# DNS failed: use only services at an IP address
			[[ ${dns_failed} == 1 && ! "${url}" =~ ^https?://[0-9.]+/ ]] && continue
			opts=(--connect-timeout 3 --max-time 6 -s)
			[[ "${filter}" == trace ]] && opts+=(-k)
			json=$(curl "${opts[@]}" "${url}")
			rc=$?
			if [[ "${filter}" == trace ]]; then
				cc=$(sed -n 's/^loc=//p' <<< "${json}")
				tz=$(awk -F'\t' -v cc="${cc}" '$1 == cc {print $3}' /usr/share/zoneinfo/zone.tab 2> /dev/null)
				[[ $(wc -l <<< "${tz}") == 1 ]] || tz=""
			else
				IFS='|' read -r tz cc < <(jq -r "${filter}" <<< "${json}" 2> /dev/null)
			fi
			[[ -n "${tz}" && -f "/usr/share/zoneinfo/${tz}" ]] || tz=""
			[[ "${cc}" =~ ^[A-Z]{2}$ ]] || cc=""
			if [[ -n "${tz}" || ( -n "${cc}" && "${filter}" == trace ) ]]; then
				echo "${tz}|${cc}"
				return 0
			fi
			logger -t armbian-firstlogin "geolocation: ${url} failed, try ${round}, curl exit ${rc}, reply: ${json:0:80}"
		done <<- EOT
			https://ipwhois.app/json/${PUBLIC_IP} "\(.timezone // "")|\(.country_code // "")"
			https://ipinfo.io/json "\(.timezone // "")|\(.country // "")"
			https://ipwho.is/ "\(.timezone.id // "")|\(.country_code // "")"
			https://get.geojs.io/v1/ip/geo.json "\(.timezone // "")|\(.country_code // "")"
			https://ipapi.co/json/ "\(.timezone // "")|\(.country_code // "")"
			http://ip-api.com/json/ "\(.timezone // "")|\(.countryCode // "")"
			https://1.1.1.1/cdn-cgi/trace trace
		EOT
		# no route to the internet: retries do not help
		ip route get 1.1.1.1 > /dev/null 2>&1 || break
		[[ ${round} -lt 3 ]] && sleep 5
	done
	return 1
}

set_timezone_and_locales() {

	# Grab this machine's public IP address
	PUBLIC_IP=$(curl --max-time 5 -s https://ipinfo.io/ip)

	# Without a connection, wireless can help. Laptops can start with the radio blocked
	# (rfkill): a soft block goes away here. A hard block (a switch or a key) stays: say so.
	if [[ -z "$PUBLIC_IP" ]]; then
		local _r _unblocked=0
		for _r in /sys/class/rfkill/rfkill*; do
			[[ "$(cat "${_r}/type" 2> /dev/null)" == wlan ]] || continue
			if [[ "$(cat "${_r}/hard" 2> /dev/null)" == 1 ]]; then
				echo -e "Wireless is \x1B[91moff\x1B[0m: turn it on with the switch or key of the device."
			elif [[ "$(cat "${_r}/soft" 2> /dev/null)" == 1 ]] && echo 0 > "${_r}/soft" 2> /dev/null; then
				_unblocked=1
			fi
		done
		# the driver needs a moment before it can scan
		[[ ${_unblocked} == 1 ]] && sleep 2
	fi

	# Check if we have wireless adaptor
	WIFI_DEVICE=$(LC_ALL=C iw dev | awk '$1=="Interface"{print $2}' 2> /dev/null)

	if [ -z "$PUBLIC_IP" ]; then

		# ask for connecting to wireless if wifi device is found
		if [[ -n "$WIFI_DEVICE" ]]; then
			echo -e "Internet connection was \x1B[91mnot detected\x1B[0m."
			echo ""
			unset response
			while [[ ! "${response}" =~ ^(Y|y|N|n)$ ]]; do
				if [[ -z $PRESET_CONNECT_WIRELESS && $preset_unattended != 1 ]]; then
					read -r -p "Connect via wireless? [Y/n] " response
					response=${response:-Y}
				else
					response=n
				fi
			done
			if [[ "${response}" =~ ^(Y|y)$ ]]; then

				# We could have multiple devices
				if (( $(grep -c . <<<"$WIFI_DEVICE") > 1 )); then
					scanning=0
					while [[ ${scanning} -lt 3 ]]; do
						scanning=$(( scanning + 1 ))
						echo -e "\nMultiple wireless adaptors detected. Choose primary:\n"
						WIFI_DEVICES=($(printf '%s\n' "${WIFI_DEVICE[@]}" | sed 's/^[ \t]*//' | sed 's/"//g' | sed 's/ESSID://' | awk 'BEGIN{FS=OFS=","} {$NF=++count OFS $NF} 1'))
						for str in "${WIFI_DEVICES[@]}"; do echo "$str" | sed "s/,/ \t /g"; done
						echo ""
						read -r -p "Enter a number of wireles adaptor: " input
						if [[ "$input" =~ ^[0-9]{,2}$ && -n "$input" ]] ; then break; fi
					done
					[[ -z $input ]] && input=1
					WIFI_DEVICE=$(echo ${WIFI_DEVICES[$input-1]} | cut -d"," -f2)
				fi

				# bring up wifi device (not done by networkd, only by NetworkManager)
				ip link set ${WIFI_DEVICE} up
				# get list of wireless networks
				scanning=0
				broken=1
				while [[ ${scanning} -lt 3 ]]; do
					sleep 0.5
					scanning=$(( scanning + 1 ))
					readarray -t ARRAY < <(iw dev ${WIFI_DEVICE} scan 2> /dev/null | egrep 'SSID' | sed 's/^[ \t]*//' | sed 's/"//g' | sed 's/SSID: //' | sed '/^$/d' | sort | uniq | awk 'BEGIN{FS=OFS=","} {$NF=++count OFS $NF} 1')
					if [[ ${#ARRAY[@]} -gt 0 ]]; then broken=0; break; fi
				done
				# wifi can also fail
				if [[ ${broken} == 1 ]]; then
					echo -e "\nWireless connection was \x1B[91mnot detected\x1B[0m.\n"
				else
					echo -e "\nDetected wireless networks:\n"
					scanning=0
					broken=1
					while [[ ${scanning} -lt 3 ]]; do
						scanning=$(( scanning + 1 ))
						while [[ 1 ]] ; do
							for str in "${ARRAY[@]}"; do echo $str | sed "s/,/ \t /"; done
							echo ""
							read -r -p "Enter a number of SSID: " input
							if [[ "$input" =~ ^[0-9]{,2}$ ]] ; then break; fi
						done
						# get password
						while [[ -n "${input}" ]] ; do
							SSID=$(echo ${ARRAY[$input-1]} | cut -d"," -f2-)
							echo ""
							read -r -p "Enter a password for ${SSID}: " password
							break
						done

						# generate config
						local _f="/etc/netplan/30-wifis-dhcp.yaml"
						if cat <<- EOF > "${_f}.tmp"
						# Created by Armbian firstlogin script
						network:
						  wifis:
						    ${WIFI_DEVICE}:
						      dhcp4: yes
						      dhcp6: yes
						      access-points:
						        "$SSID":
						         password: |-
						           ${password}
						EOF
						then
							atomic_write "${_f}.tmp" "${_f}" 600 || return 1
						else
							rm -f "${_f}.tmp"
							return 1
						fi

						# apply to netplan
						systemctl daemon-reload
						netplan apply 2>/dev/null

						# wireless link probing
						pinging=10
						broken=1
						WIRELESSLINK=""
						echo ""
						while [[ ${pinging} -gt 1 && -n "${input}" && -n "${password}" ]]; do
							pinging=$(( pinging - 1 ))
							printf "\rProbing wireless link ($pinging)"
							WIRELESSLINK=$(iw "${WIFI_DEVICE}" link 2> /dev/null | grep "$SSID")
							sleep 2
							# exit if connection is suffesful
							if [[ "${WIRELESSLINK}" == *$SSID* ]]; then
								broken=0
								break
							fi
						done

						if [[ ${broken} == 1 ]]; then
							echo -e "\n\nWireless link was \x1B[91mnot detected\x1B[0m. Wrong password or weak signal."
						fi
						# get public IP probing
						broken=1
						pinging=10

						while [[ ${pinging} -gt 1 && -n "${input}" && -n "${password}" && "${WIRELESSLINK}" == *$SSID* ]]; do
							pinging=$(( pinging - 1 ))
							printf "\rProbing internet connection ($pinging)"
							PUBLIC_IP=$(curl --max-time 5 -s https://ipinfo.io/ip)
							if [[ -n "$PUBLIC_IP" ]]; then
								broken=0
								break
							else
								sleep 5
							fi
						done
						echo ""

						if [[ ${broken} == 0 ]]; then
							break
						fi
					done

						if [[ ${broken} == 1 ]]; then
							echo -e "\n\x1B[91mUnable to connect to Access Point\x1B[0m.\n"
							rm -f /etc/netplan/30-wifis-dhcp.yaml
							netplan apply 2>/dev/null
							systemctl daemon-reload
						fi

				fi # detected or not detected wireless network
			fi
			echo ""
		fi
	fi

	# Grab IP once again if not found
	sleep 3
	[[ -z "$PUBLIC_IP" && -n "$WIFI_DEVICE" ]] && PUBLIC_IP=$(curl --max-time 5 -s https://ipinfo.io/ip)

	# Geolocation. A failed lookup yields no usable values.
	IFS='|' read -r TZDATA CCODE < <(geolocate)
	GEO_FAILED=0
	[[ -z "${TZDATA}${CCODE}" ]] && GEO_FAILED=1

	unset response
	while [[ ! "${response}" =~ ^(Y|y|N|n)$ ]]; do
		if [ -z "${SET_LANG_BASED_ON_LOCATION}" ] && [ -n "${TZDATA}${CCODE}" ] && [[ $preset_unattended != 1 ]]; then
			if [[ -n "${TZDATA}" ]]; then
				echo -e "Detected timezone: \x1B[92m$TZDATA\x1B[0m"
			else
				echo -e "Detected country: \x1B[92m$CCODE\x1B[0m"
			fi
			echo ""
			read -r -p "Set user language based on your location? [Y/n] " response
			response=${response:-Y}
		else
			# unattended without an answer: take the prompt's default (Y)
			response=${SET_LANG_BASED_ON_LOCATION:-Y}
			break
		fi
	done
	# change it only if we have a match and if we agree
	if [[ "${response}" =~ ^(N|n)$ ]]; then
		unset CCODE TZDATA
	fi

	LOCALES=$(find_locales "${CCODE}")
	# no locale for this country: offer all locales
	if [[ -z "${LOCALES}" ]]; then
		CCODE=""
		LOCALES=$(find_locales "")
	fi
	readarray -t options <<< "${LOCALES}"

	if [ -z $PRESET_LOCALE ];then
		# when having more locales, prompt for choosing one (unattended: the first)
		if [[ "${#options[@]}" -gt 1 && $preset_unattended == 1 ]]; then
			# no country code: the search matched all locales, so keep the image locale
			if [[ -n "${CCODE}" ]]; then
				LOCALES=${options[0]}
			else
				LOCALES=$(sed -n 's/^LANG=//p' /etc/default/locale | tr -d '"')
				LOCALES=${LOCALES:-C.UTF-8}
			fi
		elif [[ "${#options[@]}" -gt 1 ]]; then
			options+=("Skip generating locales")
			if [[ -n "${CCODE}" ]]; then
				echo -e "\nAt your location, more locales are possible:\n"
			elif [[ ${GEO_FAILED} == 1 ]]; then
				echo -e "\nLocation not detected. Choose a locale:\n"
			else
				echo -e "\nChoose a locale:\n"
			fi
			PS3='Please enter your choice:'
			select opt in "${options[@]}"; do
				if [[ " ${options[*]} " == *" ${opt} "* ]]; then
					LOCALES=${opt}
					break
				fi
			done
		fi
	else
		LOCALES=$PRESET_LOCALE
	fi

	if [[ "${LOCALES}" != *Skip* ]]; then

		if [ -z $PRESET_TIMEZONE ];then
			# if TZDATA was not detected, we need to select one (unattended:
			# keep the image's timezone rather than wait on tzselect)
			if [[ -z ${TZDATA} && $preset_unattended != 1 ]]; then
				TZDATA=$(tzselect | tail -1)
			fi
			echo ""
		else
			TZDATA=$PRESET_TIMEZONE
		fi

		if [[ -n ${TZDATA} ]]; then
			timedatectl set-timezone "${TZDATA}"
			dpkg-reconfigure --frontend=noninteractive tzdata > /dev/null 2>&1
		fi

		# change default locales (atomic write). On newer releases /etc/default/locale
		# is a symlink to /etc/locale.conf, and systemd-tmpfiles restores that symlink
		# at each boot: write the file it points to.
		local _f
		_f=$(readlink -f /etc/default/locale) && [[ -n "${_f}" ]] || return 1
		if sed "s/=.*/=$(echo ${LOCALES} | cut -d" " -f1)/g" "${_f}" > "${_f}.tmp"; then
			atomic_write "${_f}.tmp" "${_f}" || return 1
		else
			rm -f "${_f}.tmp"
			return 1
		fi

		# generate locales (atomic write for locale.gen)
		local _f="/etc/locale.gen"
		if sed 's/# '"${LOCALES}"'/'"${LOCALES}"'/' "${_f}" > "${_f}.tmp"; then
			atomic_write "${_f}.tmp" "${_f}" || return 1
		else
			rm -f "${_f}.tmp"
			return 1
		fi
		echo -e "Generating locales: \x1B[92m${LOCALES}\x1B[0m"
		locale-gen "${LOCALES}" > /dev/null 2>&1

		# setting detected locales only for user (idempotent)
		for rcfile in /home/"$RealUserName"/.bashrc /home/"$RealUserName"/.xsessionrc; do
			if [[ ! -e "$rcfile" ]]; then
				# Create empty file with proper ownership before appending; leave
				# ownership alone if the file already exists (user may have customized).
				touch -- "$rcfile"
				chown -- "$RealUserName":"$RealUserName" "$rcfile"
			fi
			if ! grep -q "^export LC_ALL=$LOCALES" "$rcfile" 2>/dev/null; then
				{
					cat -- "$rcfile"
					echo "export LC_ALL=$LOCALES"
					echo "export LANG=$LOCALES"
					echo "export LANGUAGE=$LOCALES"
				} > "${rcfile}.tmp" && atomic_write "${rcfile}.tmp" "$rcfile" "" "$RealUserName:$RealUserName" || return 1
			fi
		done

	fi
}

# Download SSH keys from URL $1 to $2.tmp. 0: a valid key. 1: an HTTP error or no key
# (an error page, an empty answer). 2: no network: the first login must run again.
download_keys() {
	local rc=0
	curl -fsSL --retry 5 --connect-timeout 3 "$1" > "$2.tmp" 2> /dev/null || rc=$?
	if ((rc == 0)) && ssh-keygen -lf "$2.tmp" > /dev/null 2>&1; then
		return 0
	fi
	rm -f "$2.tmp"
	case $rc in
		5 | 6 | 7 | 28 | 35 | 52 | 56) return 2 ;;
	esac
	return 1
}

add_user() {
	read -r -t 0 _
	REPEATS=3

	# Power-loss re-run: detect existing regular user, skip username prompt
	local existing_user
	existing_user=$(awk -F: '$3 >= 1000 && $1 != "nobody" {print $1; exit}' /etc/passwd)
	if [ -n "${existing_user}" ]; then
		RealUserName="${existing_user}"
		username="${existing_user}"
		echo -e "Detected existing user \e[0;92m$RealUserName\x1B[0m from previous setup, reusing."
	else
	while [ -f "/root/.not_logged_in_yet" ]; do
		[[ -z "${PRESET_USER_NAME}" ]] && echo -e "\nPlease provide a username (eg. your first name): \c"
		if [ -z "$PRESET_USER_NAME" ];then
			read -r -e username
		else
			username="$PRESET_USER_NAME"
		fi
		if ! grep '^[a-zA-Z][a-zA-Z0-9_-]*$' <<< "$username" > /dev/null; then
			echo -e "\n\x1B[91mError\x1B[0m: illegal characters in username"
			return
		fi

		RealUserName="$(echo "$username" | tr '[:upper:]' '[:lower:]' | tr -d -c '[:alnum:]_-')"
		[ -z "$RealUserName" ] && return
		if ! id "$RealUserName" > /dev/null 2>&1; then
			break
		elif [ ! -d "/home/$RealUserName" ]; then
			# Partially created user from a prior interrupted run: break and let
			# the home-repair branch below recover it. Without this, PRESET_USER_NAME
			# would loop forever on "already exists".
			break
		else
			echo -e "Username \e[0;31m$RealUserName\x1B[0m already exists on the system."
		fi
	done
	fi

	# Set default user login icon
	set_user_icon "$RealUserName"

	while [ -f "/root/.not_logged_in_yet" ]; do
		if [ -z "$PRESET_USER_PASSWORD" ];then
			read_password "Create user ($username)"
			echo ""
		else
			password="$PRESET_USER_PASSWORD"
		fi
		first_input="$password"
		if [ -z "$PRESET_USER_PASSWORD" ];then
			read_password "Repeat user ($username)"
			echo ""
		else
			password="$PRESET_USER_PASSWORD"
		fi
		second_input="$password"
		if [[ "$first_input" == "$second_input" ]]; then
			# minimal images might not have this
			if command -v cracklib-check > /dev/null 2>&1; then
				result="$(cracklib-check <<< "$password")"
				okay="$(awk -F': ' '{ print $2}' <<< "$result")"
				if [[ "$okay" != "OK" ]]; then
					echo -e "\n\e[0;31mWarning:\x1B[0m Weak password, $okay \b!"
				fi
			fi
			if [[ -z "$PRESET_DEFAULT_REALNAME" && $preset_unattended != 1 ]]; then
				echo -e ""
				read -r -e -p "Please provide your real name: " -i "${RealUserName^}" RealName
			else
				# unattended without a real name: use the prompt's default
				RealName="${PRESET_DEFAULT_REALNAME:-${RealUserName^}}"
			fi

			# Skip user creation if already exists (power-loss re-run). If the user
			# exists but home is missing (passwd written, home creation interrupted),
			# rebuild it from /etc/skel with correct ownership so the user can log in.
			if ! id "$RealUserName" > /dev/null 2>&1; then
				# useradd (Essential, from passwd) instead of adduser (optional on
				# Debian forky+, absent from minimal images). --user-group mirrors
				# adduser's per-user group; --create-home copies /etc/skel; login shell
				# comes from SHELL_PATH (set_shell ran first). Password is disabled here
				# and set right below, same as adduser --disabled-password.
				useradd --create-home --home-dir /home/"$RealUserName" --shell "$SHELL_PATH" \
					--comment "$RealName" --user-group "$RealUserName" || return 1
			elif [ ! -d "/home/$RealUserName" ]; then
				mkdir -p /home/"$RealUserName" || return 1
				cp -r /etc/skel/. /home/"$RealUserName"/ 2>/dev/null || return 1
				chown -R "$RealUserName:$RealUserName" /home/"$RealUserName" || return 1
				echo -e "Repaired missing home directory for \e[0;92m$RealUserName\x1B[0m."
			fi

			# download and add SSH key if defined
			if [[ -n "${PRESET_USER_KEY}" ]]; then
				local _f="/home/$RealUserName/.ssh/authorized_keys"
				mkdir -p /home/"$RealUserName"/.ssh/ || return 1
				chown "$RealUserName:$RealUserName" /home/"$RealUserName"/.ssh/ || return 1
				chmod 700 /home/"$RealUserName"/.ssh/ || return 1
				# No key in the answer: the account works without the keys. No network: try again.
				local _rc=0
				download_keys "${PRESET_USER_KEY}" "${_f}" || _rc=$?
				if ((_rc == 0)); then
					atomic_write "${_f}.tmp" "${_f}" 600 "$RealUserName:$RealUserName" || return 1
				elif ((_rc == 2)); then
					echo -e "\e[0;31mError:\x1B[0m cannot reach ${PRESET_USER_KEY}."
					return 1
				else
					echo -e "\e[0;31mWarning:\x1B[0m no SSH key at ${PRESET_USER_KEY}. The account has no SSH keys."
				fi
			fi

			if [[ -n "$first_input" ]]; then
				(
					echo "$first_input"
					echo "$second_input"
				) | passwd "$RealUserName" > /dev/null 2>&1
			else
				passwd -d "$RealUserName" > /dev/null 2>&1
			fi

			# Hardware and desktop groups: EXTRA_GROUPS in /etc/adduser.conf, the groups adduser gives
			# every new normal user (set by the BSP). Then the admin groups, for the first user only.
			# Not docker or disk: each gives root without a password.
			user_groups=$(sed -n 's/^[[:space:]]*EXTRA_GROUPS[[:space:]]*=[[:space:]]*//p' /etc/adduser.conf 2> /dev/null | tail -n 1 | tr -d "\"'")
			for additionalgroup in ${user_groups:-audio video plugdev input dialout netdev bluetooth render users games i2c gpio spi} sudo systemd-journal ssh; do
				usermod -aG "${additionalgroup}" "${RealUserName}" 2> /dev/null
			done

			# fix for gksu in Xenial
			touch /home/"$RealUserName"/.Xauthority
			chown "$RealUserName":"$RealUserName" /home/"$RealUserName"/.Xauthority
			RealName="$(awk -F":" "/^${RealUserName}:/ {print \$5}" < /etc/passwd | cut -d',' -f1)"
			[ -z "$RealName" ] && RealName="$RealUserName"
			echo -e "\nDear \e[0;92m${RealName}\x1B[0m, your account \e[0;92m${RealUserName}\x1B[0m has been created and is sudo enabled."
			echo -e "Please use this account for your daily work from now on.\n"
			# .not_logged_in_yet is NOT deleted here - the EXIT trap removes
			# it once FIRSTLOGIN_SUCCESS=1 is set after all config completes.
			# set up profile sync daemon on desktop systems
			if command -v psd > /dev/null 2>&1; then
				# psd 6.x mounts its overlays through psd-overlay-helper as root.
				# psd 7 and later use fuse-overlayfs, have no helper and need no sudo.
				# Grant psd-overlay-helper NOPASSWD via a sudoers drop-in (atomic write).
				# Using /etc/sudoers.d/ avoids touching /etc/sudoers directly: power-loss
				# recovery is simply "no drop-in" → re-run recreates it, and there is no
				# need to restore or validate any dist version of /etc/sudoers.
				if [[ -x /usr/bin/psd-overlay-helper ]]; then
					local _f="/etc/sudoers.d/armbian-firstlogin-psd"
					if echo "${RealUserName} ALL=(ALL) NOPASSWD: /usr/bin/psd-overlay-helper" > "${_f}.tmp"; then
						atomic_write "${_f}.tmp" "${_f}" 440 || return 1
					else
						rm -f "${_f}.tmp"
						return 1
					fi
				fi
				touch /home/"${RealUserName}"/.activate_psd
				chown "$RealUserName":"$RealUserName" /home/"${RealUserName}"/.activate_psd
			fi
			break
		elif [[ -n $password ]]; then
			echo -e "Rejected - \e[0;31mpasswords do not match.\x1B[0m Try again [${REPEATS}]."
			REPEATS=$((REPEATS - 1))
		fi
		[[ "$REPEATS" -eq 0 ]] && exit 0
	done

}

# Keyboard layout from PRESET_KEYBOARD_LAYOUT and PRESET_KEYBOARD_VARIANT (xkb names).
# armbian-firstrun-gui sets them. The console and X11 read /etc/default/keyboard.
set_keyboard() {
	[[ -n "${PRESET_KEYBOARD_LAYOUT}" ]] || return 0
	local _f="/etc/default/keyboard"
	{
		[[ -f "${_f}" ]] && grep -v -E '^(XKBLAYOUT|XKBVARIANT)=' "${_f}"
		[[ -f "${_f}" ]] || printf 'XKBMODEL="pc105"\nXKBOPTIONS=""\nBACKSPACE="guess"\n'
		echo "XKBLAYOUT=\"${PRESET_KEYBOARD_LAYOUT}\""
		echo "XKBVARIANT=\"${PRESET_KEYBOARD_VARIANT}\""
	} > "${_f}.tmp" && atomic_write "${_f}.tmp" "${_f}" 644 || return 1
	echo -e "Keyboard: \x1B[92m${PRESET_KEYBOARD_LAYOUT}${PRESET_KEYBOARD_VARIANT:+ (${PRESET_KEYBOARD_VARIANT})}\x1B[0m"
	# Console keymap now. Without console-setup it applies after the next boot.
	# A failure does not stop the first login: the file above applies at the next boot.
	if command -v setupcon > /dev/null; then
		setupcon --save -k --force < /dev/null > /dev/null 2>&1 ||
			echo "Warning: setupcon failed. The console keymap applies after the next boot."
	fi
	# X takes the layout from the udev properties of the input devices (keyboard(5)).
	# The display manager starts later in this run: refresh the properties first.
	if command -v udevadm > /dev/null; then
		udevadm trigger --subsystem-match=input --action=change > /dev/null 2>&1 &&
			udevadm settle --timeout=10 > /dev/null 2>&1
	fi
	return 0
}

# Ask the keyboard layout on a local console only. SSH and serial terminals
# use the layout of the client computer, so the answer has no effect there.
# Without setupcon the layout applies after the next boot: the passwords
# would then be typed with another layout than the next login.
ask_keyboard() {
	[[ -z "${PRESET_KEYBOARD_LAYOUT}" && "${preset_unattended}" != 1 ]] || return 0
	[[ "$(tty)" =~ ^/dev/tty[0-9]+$ ]] || return 0
	command -v setupcon > /dev/null || return 0
	local rules=/usr/share/X11/xkb/rules/base.lst current layout variant
	[[ -r "${rules}" ]] || return 0
	current=$(. /etc/default/keyboard 2> /dev/null; echo "${XKBLAYOUT:-us}")
	echo ""
	while :; do
		read -r -p "Keyboard layout and variant, ? for a list [${current}]: " layout variant
		[[ -n "${layout}" ]] || return 0
		if [[ "${layout}" == "?" ]]; then
			awk '/^! layout/{f=1; next} /^!/{f=0} f && NF {print $1}' "${rules}" | column | more
			continue
		fi
		awk -v l="${layout}" -v v="${variant}" '
			/^! layout/{s="l"; next} /^! variant/{s="v"; next} /^!/{s=""}
			s=="l" && $1==l {lok=1}
			s=="v" && $1==v && $2==l":" {vok=1}
			END {exit !(lok && (v=="" || vok))}' "${rules}" && break
		echo "Unknown layout or variant: ${layout} ${variant}"
	done
	PRESET_KEYBOARD_LAYOUT="${layout}"
	PRESET_KEYBOARD_VARIANT="${variant}"
}

# GitHub sign-in of armbian-firstrun-gui. PRESET_GIT_HOME holds the SSH key of this
# device (on the account for signed commits), known_hosts lines for github.com, the
# login name and the commit email. With the file "push", the key is on the account for
# push too, and hosts.yml holds the gh login. Without it, the device only signs commits.
# Git settings that already exist (from dotfiles) stay. A failure does not stop the setup.
# Git identity of a looked-up account without a GitHub sign-in: PRESET_GIT_EMAIL (the
# public email, or the noreply address) and the full name. No signing. Settings that
# exist (from dotfiles) stay.
set_git_identity() {
	local user="${RealUserName:-}" email="${PRESET_GIT_EMAIL:-}" home
	[[ -n $user && -n $email && -z ${PRESET_GIT_HOME:-} ]] || return 0
	command -v git > /dev/null || return 0
	home="/home/$user"
	local key value
	for key in user.name user.email; do
		runuser -u "$user" -- env HOME="$home" git config --global --get "$key" > /dev/null && continue
		[[ $key == user.name ]] && value="${RealName:-$user}" || value="$email"
		runuser -u "$user" -- env HOME="$home" git config --global "$key" "$value" ||
			echo "Warning: git $key not set"
	done
}

set_git_account() {
	local src="${PRESET_GIT_HOME:-}" user="${RealUserName:-}"
	[[ -n $src && -n $user ]] || return 0
	if [[ $src != /run/armbian-firstrun-gui.git || -L $src || ! -d $src ]]; then
		echo "Warning: PRESET_GIT_HOME is not the wizard directory, GitHub setup skipped"
		return 0
	fi
	local home="/home/$user" group login email key ok=1 pub=1 push=0 sshcfg=1
	[[ -e $src/push ]] && push=1
	# Copy a file of the preset for the user. A temporary name first: a failed copy
	# leaves no partial file that a new run would keep.
	_install() {
		install -m "$1" -o "$user" -g "$group" "$2" "$3.tmp" && mv -f "$3.tmp" "$3" || { rm -f "$3.tmp"; false; }
	}
	# Append a line. A file without a final newline gets one first.
	_append() {
		{ [[ ! -s $2 || -z $(tail -c 1 "$2") ]] || echo; echo "$1"; } >> "$2"
	}
	# Append a line with the permissions of the user: root does not change the owner.
	_append_user() {
		runuser -u "$user" -- bash -c '{ [[ ! -s $2 || -z $(tail -c 1 "$2") ]] || echo; echo "$1"; } >> "$2"' _ "$1" "$2"
	}
	group=$(id -gn "$user") || return 0
	login=$(< "$src/login") || ok=0
	email=$(< "$src/email") || ok=0
	# Without an email, git gets no identity and no signer entry. The files stay for a new try.
	[[ -n $email ]] || ok=0
	echo "GitHub: setting up the account ${login} on this device"

	mkdir -p "$home/.ssh" && chown "$user:$group" "$home/.ssh" && chmod 700 "$home/.ssh" || ok=0
	# An existing default key stays: the device key then gets its own name, and SSH
	# uses it for github.com. A new run after a failure finds the same key again.
	key="$home/.ssh/id_ed25519"
	if [[ -e $key ]] && ! cmp -s "$key" "$src/id_ed25519"; then
		key="$home/.ssh/id_ed25519_github"
		if [[ -e $key ]] && ! cmp -s "$key" "$src/id_ed25519"; then
			echo "Warning: $key exists, GitHub setup skipped"
			unset -f _append _append_user _install
			return 0
		fi
	fi
	# OpenSSH tries the identities in order: a key from the dotfiles for another account
	# can log in first. The device key must be the first identity for a push (git@github.com).
	local first
	first=$(runuser -u "$user" -- env HOME="$home" ssh -G git@github.com 2> /dev/null | grep -m1 '^identityfile ')
	first=${first#identityfile }
	if ((push)) && [[ $first != "$key" && $first != "~/.ssh/${key##*/}" ]]; then
		# The block goes first. "Host *" then gives the rest of the file its global scope again.
		runuser -u "$user" -- bash -c 'old=$(cat "$1" 2> /dev/null) || old=
			{ printf "Host github.com\n\tIdentityFile %s\n" "$2"; [[ -z $old ]] || printf "Host *\n%s\n" "$old"; } > "$1" &&
			chmod 600 "$1"' _ "$home/.ssh/config" "$key" || ok=0 sshcfg=0
	fi
	# Signing needs both halves of the key.
	_install 600 "$src/id_ed25519" "$key" || ok=0 pub=0
	_install 644 "$src/id_ed25519.pub" "$key.pub" || ok=0 pub=0
	local line
	while IFS= read -r line; do
		grep -qxF -- "$line" "$home/.ssh/known_hosts" 2> /dev/null || _append "$line" "$home/.ssh/known_hosts" || ok=0
	done < "$src/known_hosts" || ok=0
	[[ -e $home/.ssh/known_hosts ]] && chown "$user:$group" "$home/.ssh/known_hosts"

	# The gh login: gh works at once, also when it is installed later.
	if [[ -f $src/hosts.yml && ! -e $home/.config/gh/hosts.yml ]]; then
		mkdir -p "$home/.config/gh" &&
			_install 600 "$src/hosts.yml" "$home/.config/gh/hosts.yml" &&
			chown "$user:$group" "$home/.config" "$home/.config/gh" || ok=0
	fi

	if command -v git > /dev/null; then
		_git_get() { runuser -u "$user" -- env HOME="$home" git config --global --get "$1"; }
		# A failed write counts as a failure of the setup.
		_git_set() {
			_git_get "$1" > /dev/null && return 0
			runuser -u "$user" -- env HOME="$home" git config --global "$1" "$2" && return 0
			ok=0
			return 1
		}
		_git_set user.name "${RealName:-$login}"
		[[ -z $email ]] || _git_set user.email "$email"
		# Pushes to GitHub use the key of this device. Clones stay anonymous.
		((!pub || !push || !sshcfg)) || _git_set url.git@github.com:.pushInsteadOf https://github.com/
		# Sign with the key of this device, unless the dotfiles chose another signing key
		# or another format (OpenPGP). The key of this device: a new run completes the setup.
		local format signing
		format=$(_git_get gpg.format) || true
		signing=$(_git_get user.signingkey) || true
		if ((!pub)); then
			ok=0
		elif [[ (-z $signing || $signing == "$key.pub") && (-z $format || $format == ssh) ]]; then
			# Signing on only when the key settings are written.
			if _git_set gpg.format ssh && _git_set user.signingkey "$key.pub"; then
				_git_set commit.gpgSign true
				_git_set tag.gpgSign true
			fi
			# Local check of the signatures: git log --show-signature. Existing entries stay.
			_git_set gpg.ssh.allowedSignersFile "$home/.ssh/allowed_signers"
			local signers entry
			signers=$(_git_get gpg.ssh.allowedSignersFile) || true
			signers="${signers/#\~/$home}"
			entry="$email namespaces=\"git\" $(< "$key.pub")"
			# A relative path is in each repository: it stays as it is.
			if [[ -n $email && $signers == /* ]] && ! grep -qxF -- "$entry" "$signers" 2> /dev/null; then
				# A shared file (for example /etc/git/allowed_signers) keeps its owner and mode.
				if ! _append_user "$entry" "$signers" 2> /dev/null; then
					echo "Warning: $user cannot write $signers, no signer entry"
					[[ $signers != "$home/.ssh/allowed_signers" ]] || ok=0
				fi
			fi
		fi
		unset -f _git_get _git_set
	else
		# No git: no identity and no signing. The files stay for a new try.
		echo "Warning: git is not installed, Git setup skipped"
		ok=0
	fi
	unset -f _append _append_user _install
	# Keep the files after a failure: nothing is lost before a new try. A reboot clears /run.
	if ((ok)); then
		rm -rf "$src"
	else
		echo "Warning: GitHub setup incomplete, the files stay in $src"
	fi
}

set_user_icon() {
    local U="$1"
    local ICON_SRC="/usr/share/armbian/armbian-user-icon.png"
    local ICON_DST="/var/lib/AccountsService/icons/$U"
    local META="/var/lib/AccountsService/users/$U"

    # If the icon doesn't exist, do nothing.
    [ -f "$ICON_SRC" ] || return 0

    mkdir -p /var/lib/AccountsService/icons /var/lib/AccountsService/users

    # Copy icon
    install -m 0644 "$ICON_SRC" "$ICON_DST"

    # Write AccountsService metadata
	cat <<- EOF > "$META"
	[User]
	Icon=$ICON_DST
	SystemAccount=false
	EOF
    chown root:root "$ICON_DST" "$META"
    chmod 0644 "$ICON_DST" "$META"
}


if [[ -f /root/.not_logged_in_yet ]] && tty -s; then

	. /root/.not_logged_in_yet

	# A complete preset has nobody at the console. Resolve a remote preset
	# before deciding, so a partial preset still waits for its missing input;
	# an ssh login already has a user.
	armbian_firstlogin_prepare_preset
	if [[ -s /run/armbian-firstlogin-preset.conf ]]; then
		. /run/armbian-firstlogin-preset.conf
	fi
	# tty1 with a screen and the text wizard: the setup starts at once, as the graphical
	# wizard on desktop images. Other consoles (serial) wait for Enter: nobody may watch them.
	firstlogin_now=0
	if [[ "$(tty)" == /dev/tty1 ]] && command -v armbian-firstrun-gui > /dev/null &&
		{ compgen -G '/dev/dri/card*' > /dev/null || [[ -e /dev/fb0 ]]; }; then
		firstlogin_now=1
	fi
	if ! armbian_firstlogin_preset_unattended && [[ -z "${SSH_CONNECTION}" && ${firstlogin_now} == 0 ]]; then
		echo -e "\nPress Enter to start the first login setup on this console."
		until read -r -t 1 _; do
			(($? > 128)) || exit 0 # not a timeout: the terminal is gone
			# done elsewhere: log out instead of leaving a root shell
			[[ -f /root/.not_logged_in_yet ]] || { kill -HUP "$PPID"; exit 0; }
		done
	fi

	# Another console takes the setup over: it reserved the next session. The reservation
	# ends when its wizard holds the lock, else after 30 s.
	firstlogin_reserved() {
		local f=/run/armbian-firstrun-gui.takeover
		[[ -f $f && "$(< $f)" != "$(tty)" && $(($(date +%s) - $(stat -c %Y $f))) -lt 30 ]]
	}

	# The text wizard runs on another console. While it asks, the setup can continue here:
	# the other wizard ends. Else this console waits, and logs out when the setup is done.
	# Returns when the other console left the setup unfinished.
	firstlogin_elsewhere() {
		local pid="" holder="" state="" reply i
		# A takeover runs: its wizard starts in a moment.
		for i in $(seq 1 30); do
			firstlogin_reserved || break
			sleep 1
		done
		[[ -f /run/armbian-firstrun-gui.text-pid ]] && read -r pid holder state < /run/armbian-firstrun-gui.text-pid
		# During a takeover the reservation names the console.
		[[ -z "${holder}" && -f /run/armbian-firstrun-gui.takeover ]] && holder=$(< /run/armbian-firstrun-gui.takeover)
		[[ -z "${holder}" ]] && holder=$(< /run/armbian-firstlogin.lock)
		# A console login starts with the automatic login line and old text: a clean screen.
		[[ -z "${SSH_CONNECTION}" ]] && clear
		echo -e "\nThe first-run setup runs on ${holder:-another console}."
		if [[ "${state}" == asking ]]; then
			# The answer can wait long: when the setup ends elsewhere meanwhile, log out.
			echo -n "Continue it here? [y/N] "
			reply=""
			until read -r -t 1 reply; do
				(($? > 128)) || break # not a timeout: the terminal is gone
				if [[ ! -f /root/.not_logged_in_yet ]]; then
					echo
					[[ -z "${SSH_CONNECTION}" ]] && kill -HUP "$PPID"
					exit 0
				fi
			done
			# The reservation keeps the other console from starting its wizard again first.
			[[ "${reply}" == [yY]* ]] && tty > /run/armbian-firstrun-gui.takeover
			if [[ "${reply}" == [yY]* ]] && kill "${pid}" 2> /dev/null; then
				for i in $(seq 1 20); do
					flock -n /run/armbian-firstlogin.lock true && return 0
					sleep 0.5
				done
			fi
		fi
		echo "This console logs out when the setup is complete."
		trap '' INT
		while [[ -f /root/.not_logged_in_yet ]] && { firstlogin_reserved || ! flock -n /run/armbian-firstlogin.lock true; }; do
			sleep 1
		done
		trap '_firstlogin_cleanup; exit' HUP INT TERM
		if [[ ! -f /root/.not_logged_in_yet ]]; then
			[[ -z "${SSH_CONNECTION}" ]] && kill -HUP "$PPID"
			exit 0
		fi
	}

	# The text wizard of armbian-firstrun-gui: the pages of the graphical wizard on this
	# terminal. It writes the answers as presets and runs this script, which applies them.
	# One console at a time: the wizard holds the lock for its session. Without the
	# wizard, or when it stops: the questions below. A preset with any credential keeps
	# the questions below: the wizard would replace it. The wizard of the service on tty1
	# that ended without a setup (Ctrl-C) leaves the questions below.
	if [[ -z "${ARMBIAN_FIRSTLOGIN_LOCKED}" ]] && ! armbian_firstlogin_preset_unattended &&
		[[ "${TERM:-dumb}" != dumb ]] &&
		[[ -z "${PRESET_ROOT_PASSWORD}${PRESET_USER_NAME}${PRESET_USER_PASSWORD}" ]] &&
		[[ ! -e /run/armbian-firstrun-gui.text-left ]] &&
		command -v armbian-firstrun-gui > /dev/null &&
		! grep -q 'armbian-firstrun-gui\.service' /proc/self/cgroup 2> /dev/null; then
		while :; do
			if firstlogin_reserved || { [[ -f /run/armbian-firstrun-gui.text-pid ]] && ! flock -n /run/armbian-firstlogin.lock true; }; then
				firstlogin_elsewhere
			fi
			# SIGINT must not run the exit trap of this script: the questions below follow.
			trap ':' INT
			armbian-firstrun-gui --text
			wizard_rc=$?
			trap '_firstlogin_cleanup; exit' HUP INT TERM
			case ${wizard_rc} in
				# 3: another console holds the setup. 4: another console took it over.
				3) [[ -f /run/armbian-firstrun-gui.text-pid ]] && continue ;;
				4)
					echo -e "\nThe setup continues on another console."
					firstlogin_elsewhere
					continue
					;;
			esac
			break
		done
		if [[ ${wizard_rc} == 0 && ! -f /root/.not_logged_in_yet ]]; then
			start_desktop_later
			# A desktop started: a console login ends. Else the login shows the motd.
			# The setup links display-manager.service and starts it with --no-block: the
			# link counts, the unit can still be activating.
			if [[ -e /etc/systemd/system/display-manager.service ]]; then
				[[ -z "${SSH_CONNECTION}" ]] && kill -HUP "$PPID"
				exit 0
			fi
			clear
			run-parts --lsbsysinit /etc/update-motd.d 2> /dev/null
			exit 0
		fi
		. /root/.not_logged_in_yet
	fi

	# The text wizard runs this script with its answers and holds the lock for it.
	if [[ "${ARMBIAN_FIRSTLOGIN_LOCKED}" != 1 ]]; then
		exec 9<> /run/armbian-firstlogin.lock || exit 1
		# The setup runs on another console: wait for it. A console logs out when it is
		# done. When the other console leaves it unfinished, the setup continues here.
		until flock -n 9; do
			firstlogin_elsewhere
		done
		tty > /run/armbian-firstlogin.lock
	fi
	firstlogin_tty=$(< /run/armbian-firstlogin.lock)
	# done elsewhere meanwhile: log a console out, keep an ssh shell
	if [[ ! -f /root/.not_logged_in_yet ]]; then
		[[ -z "${SSH_CONNECTION}" ]] && kill -HUP "$PPID"
		exit 0
	fi

	# The graphical wizard can ask on the screen while a setup starts here, for
	# example on a serial console that logged in before the wizard started. This
	# setup holds the lock, so the wizard does not apply answers now: stop it.
	# Not in the run of the wizard itself, which is in the cgroup of its service.
	if ! grep -q 'armbian-firstrun-gui\.service' /proc/self/cgroup 2> /dev/null &&
		systemctl -q is-active armbian-firstrun-gui.service 2> /dev/null; then
		echo -e "\nThe setup on the screen stops. The setup continues here."
		systemctl stop armbian-firstrun-gui.service
	fi

	. /root/.not_logged_in_yet

	# override configuration from URL; reuse the gadget helper's validated
	# download when available so both stages evaluate the same configuration.
	if [[ -n "${PRESET_CONFIGURATION}" ]]; then
		_f="/root/.not_logged_in_yet"
		if [[ "${firstlogin_tty#/dev/}" == ttyGS* &&
			-s /run/armbian-firstlogin-preset.conf && -s /run/armbian-firstlogin-preset.url &&
			"$(< /run/armbian-firstlogin-preset.url)" == "${PRESET_CONFIGURATION}" ]]; then
			atomic_write /run/armbian-firstlogin-preset.conf "${_f}" 600 || exit 1
		elif curl --fail --location --retry 5 --connect-timeout 3 --max-time 60 "${PRESET_CONFIGURATION}" > "${_f}.tmp" 2> /dev/null && bash -n "${_f}.tmp"; then
			atomic_write "${_f}.tmp" "${_f}" 600 || exit 1
		else
			rm -f "${_f}.tmp"
			exit 1
		fi
		. "${_f}"
	fi

	# A preset (e.g. written by Armbian Imager) drives an unattended run: on a
	# headless board the autologin console has nobody at it, so any question the
	# preset doesn't answer would block first login forever. With one, questions
	# the preset leaves open take their default instead of waiting for input.
	preset_unattended=0
	[[ -n "${PRESET_ROOT_PASSWORD}${PRESET_USER_NAME}" ]] && preset_unattended=1

	do_firstrun_automated_network_configuration || exit 1

	# disable autologin (remove both generic and tty-specific paths)
	rm -f /etc/systemd/system/getty@.service.d/override.conf
	rm -f /etc/systemd/system/getty@tty1.service.d/override.conf
	rm -f /etc/systemd/system/serial-getty@.service.d/override.conf
	rm -f /etc/systemd/system/serial-getty@ttyGS0.service.d/override.conf
	systemctl daemon-reload

	# daemon-reload only changes future spawns. A gadget getty on another console
	# may still be blocked in agetty -w with the old --autologin root arguments;
	# its next CR would bypass login with the marker soon gone. Restart those
	# gettys, but not this console: its login session belongs to the same running
	# service even after agetty has exec'ed login. Once this session logs out, its
	# next agetty uses the reloaded non-autologin configuration.
	systemctl list-units 'serial-getty@ttyGS*.service' --state=running --no-legend --plain 2>/dev/null |
		while read -r unit _; do
			[[ $unit == "serial-getty@${firstlogin_tty#/dev/}.service" ]] && continue || true
			systemctl try-restart "$unit"
		done

	declare desktop_dm="none"
	declare -i desktop_is_sddm=0 desktop_is_lightdm=0 desktop_is_gdm3=0
	if [[ -f /usr/bin/sddm ]]; then
		desktop_dm="sddm"
		desktop_is_sddm=1
	fi
	if [[ -f /usr/sbin/lightdm ]]; then
		desktop_dm="lightdm"
		desktop_is_lightdm=1
	fi
	if [[ -f /usr/sbin/gdm3 ]]; then
		desktop_dm="gdm3"
		desktop_is_gdm3=1
	fi
	# COSMIC login screen on greetd.
	if [[ -f /usr/lib/systemd/system/cosmic-greeter.service ]]; then
		desktop_dm="cosmic-greeter"
	fi
	# Cutefish login screen.
	if [[ -f /usr/bin/cutefish-dm ]]; then
		desktop_dm="cutefish-dm"
	fi

	echo -e "\nWaiting for system to finish booting ..."
	systemctl is-system-running --wait > /dev/null

	# enable networkManager-wait-online.service
	# When NM is used the NetworkManager-wait-online.service must be enabled so that network-online.target is not reached until
	# NetworkManager has brought up all the interfaces. Service units that require the network to be up before starting rely
	# on network-online.target working correctly otherwise they will likely fail on boot
	# Same goes for systemd-networkd stack
	# https://github.com/armbian/build/issues/7896
	if
		systemctl is-enabled --quiet NetworkManager &&
		! systemctl is-enabled --quiet NetworkManager-wait-online
	then
		systemctl enable --quiet NetworkManager-wait-online
		# @TODO: determine if there is any value in starting it now
		echo "Waiting for network startup to complete..."
		systemctl start NetworkManager-wait-online
	fi

	if
		systemctl is-enabled --quiet systemd-networkd &&
		! systemctl is-enabled --quiet systemd-networkd-wait-online
	then
		systemctl enable --quiet systemd-networkd-wait-online
		# @TODO: determine if there is any value in starting it now
		echo "Waiting for network startup to complete..."
		systemctl start systemd-networkd-wait-online
	fi

	# Enable HiDPI support only if the framebuffer size is detectable
	FB_VIRTUAL_SIZE="/sys/class/graphics/fb0/virtual_size"
	HIDPI_THRESHOLD="1920"
	if [[ -r "$FB_VIRTUAL_SIZE" ]]; then
		fb_virtual_width=$(cut -d, -f1 < "$FB_VIRTUAL_SIZE" 2>/dev/null)
		if [[ "$fb_virtual_width" =~ ^[0-9]+$ && "$fb_virtual_width" -gt "${HIDPI_THRESHOLD}" ]]; then
			# Enable HiDPI in LightDM slick-greeter
			if [[ -f /etc/lightdm/slick-greeter.conf ]]; then
				if ! grep -q "^enable-hidpi *= *on" /etc/lightdm/slick-greeter.conf; then
					echo "enable-hidpi = on" >> /etc/lightdm/slick-greeter.conf
				fi
			fi

			# Set XFCE scaling factor in skeleton config
			XFCE_XSETTINGS="/etc/skel/.config/xfce4/xfconf/xfce-perchannel-xml/xsettings.xml"
			if [[ -f "$XFCE_XSETTINGS" ]]; then
				sed -i 's|\(name="WindowScalingFactor" type="int" value="\)[0-9]*"|\12"|' "$XFCE_XSETTINGS"
			fi
			# xfwm4 does not scale its theme. Use its 2x theme.
			XFCE_XFWM4="/etc/skel/.config/xfce4/xfconf/xfce-perchannel-xml/xfwm4.xml"
			if [[ -f "$XFCE_XFWM4" && -d /usr/share/themes/Default-xhdpi/xfwm4 ]]; then
				sed -i 's|\(name="theme" type="string" value="\)[^"]*"|\1Default-xhdpi"|' "$XFCE_XFWM4"
			fi

			# Larger console font. console-setup applies /etc/default/console-setup at
			# each boot: a setfont alone is lost at the reboot and works on this tty only.
			if [[ -f /etc/default/console-setup ]] && command -v setupcon > /dev/null &&
				compgen -G "/usr/share/consolefonts/*-TerminusBold32x16.psf.gz" > /dev/null; then
				sed -i -e 's/^FONTFACE=.*/FONTFACE="TerminusBold"/' -e 's/^FONTSIZE=.*/FONTSIZE="16x32"/' \
					/etc/default/console-setup
				setupcon --force --save -f < /dev/null > /dev/null 2>&1
			elif [[ -f /usr/share/consolefonts/Uni3-TerminusBold32x16.psf.gz ]]; then
				setfont /usr/share/consolefonts/Uni3-TerminusBold32x16.psf.gz
			fi
		fi
	fi

	clear

	# In case VENDORPRETTYNAME is defined, display that
	[[ -n "${VENDORPRETTYNAME}" ]] && VENDOR="$VENDORPRETTYNAME"
	echo -e "Welcome to \e[1m\e[97m${VENDOR}\x1B[0m! \n"
	echo -e "Documentation: \e[1m\e[92m${VENDORDOCS}\x1B[0m | Community support: \e[1m\e[92m${VENDORSUPPORT}\x1B[0m\n"

	echo "" # empty line

	# Try to get the local IP address (script halts until IP was found or x retries were done)
	get_local_ip_addr

	if systemctl is-active --quiet armbian-web-config.service; then
		WEB_SSID="$(cat /etc/hostname)-armbiansetup"
		echo -e "\n\e[1m\e[96mWeb Configuration Available!\x1B[0m"
		echo -e "Connect to Wi-Fi SSID: \e[1m\e[92m${WEB_SSID}\x1B[0m"
		echo -e "Then open \e[1mhttp://10.42.0.1\x1B[0m in your browser"
		echo -e "Or continue with CLI setup below...\n"
	fi

	# A password typed here must use the layout of the next console login:
	# set the keymap first. With preset passwords (the graphical wizard), it
	# comes after the locales, where the wizard expects the "Keyboard:" line.
	keyboard_done=0
	if [[ -z "$PRESET_ROOT_PASSWORD" || -z "$PRESET_USER_PASSWORD" ]]; then
		ask_keyboard
		set_keyboard || exit 1
		keyboard_done=1
	fi

	[[ -z "$PRESET_ROOT_PASSWORD" ]] && echo "" # empty line

	# extra Enter presses would be read as an empty password
	while read -r -t 0 _; do read -r _; done

	trap '' 2
	REPEATS=3
	while [ -f "/root/.not_logged_in_yet" ]; do
		. /root/.not_logged_in_yet
		if [ -z "$PRESET_ROOT_PASSWORD" ];then
			read_password "Create root"
		else
			# allow automated install also in interactive session
			#if [ "$(who am i | awk '{print $2}')" != "tty1" ];then
			#	exit
			#fi
			password="$PRESET_ROOT_PASSWORD"
			# download SSH key if defined
			if [[ -n "${PRESET_ROOT_KEY}" ]]; then
				mkdir -p /root/.ssh/
				_f="/root/.ssh/authorized_keys"
				# As for PRESET_USER_KEY. No network: the first login runs again at the next login.
				_rc=0
				download_keys "${PRESET_ROOT_KEY}" "${_f}" || _rc=$?
				if ((_rc == 0)); then
					atomic_write "${_f}.tmp" "${_f}" 600 || exit 1
				elif ((_rc == 2)); then
					echo -e "\e[0;31mError:\x1B[0m cannot reach ${PRESET_ROOT_KEY}. Retrying on next login."
					exit 1
				else
					echo -e "\e[0;31mWarning:\x1B[0m no SSH key at ${PRESET_ROOT_KEY}. Root has no new SSH keys."
				fi
			fi
		fi

		# enable motd
		chmod +x /etc/update-motd.d/*

		first_input="$password"
		if [ -z "$PRESET_ROOT_PASSWORD" ];then
			echo ""
			read_password "Repeat root"
			echo ""
		else
			password="$PRESET_ROOT_PASSWORD"
		fi
		second_input="$password"
		if [[ "$first_input" == "$second_input" ]]; then
			# minimal might not have this
			if command -v cracklib-check > /dev/null 2>&1; then
				result="$(cracklib-check <<< "$password")"
				okay="$(awk -F': ' '{ print $2}' <<< "$result")"
				if [[ "$okay" != "OK" ]]; then
					echo -e "\n\e[0;31mWarning:\x1B[0m Weak password, $okay \b!"
				fi
			fi
			(
				echo "$first_input"
				echo "$second_input"
			) | passwd root > /dev/null 2>&1
			break
		elif [[ -n $password ]]; then
			echo -e "Rejected - \e[0;31mpasswords do not match.\x1B[0m Try again [${REPEATS}]."
			REPEATS=$((REPEATS - 1))
		fi
		[[ "$REPEATS" -eq 0 ]] && exit
	done
	trap - INT

	# display support status
	if [ "$IMAGE_TYPE" != "nightly" ]; then
		if [[ "$BRANCH" == "edge" ]]; then
			echo -e "\nSupport status: \e[0;31mcommunity support\x1B[0m (edge kernel branch)"
		elif [[ "$DISTRIBUTION_STATUS" != "supported" ]]; then
			echo -e "\nSupport status: \e[0;31mcommunity support\x1B[0m (unsupported userspace)"
		elif [[ "$BOARD_TYPE" != "conf" ]]; then
			echo -e "\nSupport status: \e[0;31mcommunity support\x1B[0m (looking for a dedicated maintainer)"
		fi
	else

		echo -e "\e[0;31m\nDeveloper Preview Build\x1B[0m\n"
		echo -e "This Armbian image was generated automatically for development and testing purpose."
		echo -e "It may include unfinished features or unstable components.\n"
		echo -e "If you are not here to report issues or just test it, \e[0;31mplease do not use this image in production.\x1B[0m"
		echo -e "Expect things to change — or even break — as improvements are made."

	fi

	# ask user to select shell
	trap '' 2
	set_shell || exit 1
	trap - INT

	trap check_abort INT

	if [ -f "/root/.not_logged_in_yet" ]; then
		[[ -z "${PRESET_USER_NAME}" ]] && echo -e "\nCreating a new user account. Press <Ctrl-C> to abort"
		[[ "${desktop_dm}" != "none" ]] && echo -e "\n\e[0;31mDesktop environment will not be enabled if you abort the new user creation\x1B[0m"
		add_user
		if [[ $? -ne 0 || -z "${RealUserName:-}" ]]; then
			echo -e "\nUser creation failed. Retrying on next login."
			exit 1
		fi
	fi
	trap - INT

	# ask user to select automated locales or not
	trap '' 2
	set_timezone_and_locales || exit 1
	[[ "${keyboard_done}" == 1 ]] || set_keyboard || exit 1
	trap - INT

	if [[ ${USER_SHELL} == zsh ]]; then
		printf "\nYou selected \e[0;91mZSH\x1B[0m as your default shell. If you want to use it right away, please logout and login! \n\n"
	fi

	# Heal host keys torn by power loss during firstrun's regeneration: the
	# teardown (rm/truncate) can be durable while recreation is lost. -A skips
	# files that exist, so drop empties first; it is a no-op on intact keys.
	for _k in /etc/ssh/ssh_host_*_key; do
		[[ -e "$_k" && ! -s "$_k" ]] || continue
		if rm -f "$_k" "$_k.pub"; then
			EMPTY_KEYS=1
		else
			echo "WARNING: failed to remove empty host key ${_k}" >&2
		fi
	done
	if [[ -n "${EMPTY_KEYS:-}" ]]; then
		echo -e "\nRegenerating SSH host keys lost to power failure..."
	fi
	ssh-keygen -A > /dev/null 2>&1 && sync

	# re-enable passing locale environment via ssh (atomic write)
	_f="/etc/ssh/sshd_config"
	if sed -E '/^[[:blank:]]*#[[:blank:]]*AcceptEnv[[:blank:]]+LANG/ s/^[[:blank:]]*#[[:blank:]]*//' "${_f}" > "${_f}.tmp"; then
		atomic_write "${_f}.tmp" "${_f}" || exit 1
	else
		rm -f "${_f}.tmp"
		exit 1
	fi
	# The SSH keys of the account (PRESET_USER_KEY) open root too, whatever the local
	# username is. Keys that root has already stay.
	_k="/home/${RealUserName}/.ssh/authorized_keys"
	if [[ -n "${PRESET_USER_KEY:-}" && -n "${RealUserName:-}" && -s "${_k}" ]]; then
		mkdir -p /root/.ssh && chmod 700 /root/.ssh || exit 1
		_f=/root/.ssh/authorized_keys
		# A temporary file: a power loss leaves no half line.
		(
			# A failed copy or write ends the subshell: the original file stays.
			if [[ -s "${_f}" ]]; then
				cat "${_f}" || exit 1
				# A file without a final newline gets one first.
				[[ -z "$(tail -c 1 "${_f}")" ]] || echo || exit 1
			fi
			while IFS= read -r _line || [[ -n "${_line}" ]]; do
				[[ -n "${_line}" && "${_line}" != \#* ]] || continue
				grep -qxF -- "${_line}" "${_f}" 2> /dev/null || echo "${_line}" || exit 1
			done < "${_k}" || exit 1
		) > "${_f}.tmp" && atomic_write "${_f}.tmp" "${_f}" 600 || { rm -f "${_f}.tmp"; exit 1; }
	fi
	# PRESET_DISABLE_ROOT_SSH_PASSWORD=yes: root logs in over SSH with a key only. Else nothing changes. The
	# drop-in is read before "PermitRootLogin yes" of the image: sshd uses the first value.
	if [[ "${PRESET_DISABLE_ROOT_SSH_PASSWORD:-}" == yes ]]; then
		# Without a key, key-only would close root SSH: an empty or failed key download
		# gives an empty list. Keys that root had before count too.
		# Only valid keys without options count: sshd can refuse or limit a key with options.
		# Only key types that sshd accepts for root count: no certificates, no DSA. An RSA key
		# works with rsa-sha2-256 or rsa-sha2-512. ssh-keygen gets the key type and the key data only.
		_n=$({
			ssh -Q key-plain
			echo --
			sshd -T -C user=root,host=localhost,addr=127.0.0.1 | awk '$1 ~ /^pubkeyaccepted(algorithms|keytypes)$/ { gsub(",", "\n", $2); print $2 }'
			echo --
			cat /root/.ssh/authorized_keys
		} 2> /dev/null | awk '
			$0 == "--" { part++; next }
			part == 0 { t[$1]; next }
			part == 1 { a[$1]; if ($1 ~ /^rsa-sha2-(256|512)$/) a["ssh-rsa"]; next }
			($1 in t) && ($1 in a) && !($2 in t) { print $1, $2 }' | ssh-keygen -lf - 2> /dev/null | wc -l)
		# "01-": before other drop-ins, for example 50-cloud-init.conf. The first value wins.
		# A drop-in of an earlier run goes when key-only is not possible: the warnings stay true.
		_f="/etc/ssh/sshd_config.d/01-armbian-root-ssh.conf"
		if ((${_n:-0} == 0)); then
			rm -f "${_f}"
			echo "Warning: root has no SSH key, root password login over SSH stays"
		elif command -v sshd > /dev/null && ! sshd -t 2> /dev/null; then
			rm -f "${_f}"
			echo "Warning: the sshd configuration has an error, root password login over SSH stays"
		elif command -v sshd > /dev/null && ! sshd -T -C user=root,host=localhost,addr=127.0.0.1 2> /dev/null |
			awk '$1 == "authorizedkeysfile" { for (i = 2; i <= NF; i++) if ($i ~ /^(\.ssh|%h\/\.ssh|\/root\/\.ssh)\/authorized_keys$/) f = 1 } END { exit !f }'; then
			# The keys above are in a file that sshd does not read for root.
			rm -f "${_f}"
			echo "Warning: sshd reads the SSH keys of root from another file, root password login over SSH stays"
		elif command -v sshd > /dev/null && [[ $(sshd -T -C user=root,host=localhost,addr=127.0.0.1 2> /dev/null |
			awk '$1 == "pubkeyauthentication" { print $2 }') != yes ]]; then
			# Without key login, key-only would close root SSH.
			rm -f "${_f}"
			echo "Warning: sshd does not accept SSH keys for root, root password login over SSH stays"
		elif command -v sshd > /dev/null && ! sshd -T -C user=root,host=localhost,addr=127.0.0.1 2> /dev/null |
			awk '$1 == "authenticationmethods" {
				# "any", or one list without password and keyboard-interactive: a key alone is enough.
				for (i = 2; i <= NF; i++) {
					if ($i == "any") f = 1
					n = split($i, m, ","); k = 1
					for (j = 1; j <= n; j++) if (m[j] ~ /^(password|keyboard-interactive)/) k = 0
					if (k) f = 1
				}
			} END { exit !f }'; then
			# AuthenticationMethods needs a password too: key-only would close root SSH.
			rm -f "${_f}"
			echo "Warning: sshd needs a password for root (AuthenticationMethods), root password login over SSH stays"
		elif grep -qE '^[[:blank:]]*Include[[:blank:]]+/etc/ssh/sshd_config\.d/' /etc/ssh/sshd_config; then
			if printf '%s\n' "# armbian-firstlogin: root logs in over SSH with a key only. Read before sshd_config: this value wins." \
				"PermitRootLogin prohibit-password" > "${_f}.tmp"; then
				atomic_write "${_f}.tmp" "${_f}" 644 || exit 1
			else
				rm -f "${_f}.tmp"
				exit 1
			fi
			# A configuration that sshd refuses must not stop SSH: the drop-in goes again.
			if command -v sshd > /dev/null && ! sshd -t 2> /dev/null; then
				rm -f "${_f}"
				echo "Warning: sshd does not accept the configuration, root password login over SSH stays"
			else
				_root_ssh_key_only=1
			fi
		else
			echo "Warning: sshd_config does not include sshd_config.d, root password login over SSH stays"
		fi
	fi
	# Restart ssh.service; on failure preserve /root/.not_logged_in_yet so
	# firstlogin reruns for recovery. Unlike reload, restart succeeds on an
	# inactive unit, so this does not loop on a fresh image.
	systemctl restart ssh.service || exit 1
	# The effective value: another setting can still win (a Match block, the user's file).
	if [[ "${_root_ssh_key_only:-}" == 1 ]] && command -v sshd > /dev/null; then
		# Root from this host (Match User root), over SSH from the client's address too
		# (Match Address), and the global value.
		_value=$({
			for _a in 127.0.0.1 ${SSH_CONNECTION:+"${SSH_CONNECTION%% *}"}; do
				sshd -T -C "user=root,host=localhost,addr=${_a}"
			done
			sshd -T
		} 2> /dev/null | awk '$1 == "permitrootlogin" && $2 == "yes" { print; exit }')
		if [[ -n "${_value}" ]]; then
			echo "Warning: root password login over SSH is still allowed: another sshd setting wins"
		fi
		# A Match Host block depends on the name of the client: sshd -T cannot check it here.
		if cat /etc/ssh/sshd_config /etc/ssh/sshd_config.d/*.conf 2> /dev/null |
			grep -qiE '^[[:blank:]]*Match[[:blank:]]+(.*[[:blank:]])?Host([[:blank:]]|=)'; then
			echo "Warning: a Match Host block in the sshd configuration can allow root password login. Check it."
		fi
	fi
	# All critical configuration is complete. The EXIT trap may now safely
	# remove the marker; subsequent failures (DM startup, etc.) should not
	# force a full firstlogin rerun.
	FIRSTLOGIN_SUCCESS=1
	release_rootfs_resize

	# Git and GitHub setup last: dotfiles applied before it can bring a .gitconfig.
	# Settings that exist stay. A failure does not stop the first login.
	set_git_account
	set_git_identity

	# rpardini: hacks per-dm, very much legacy stuff that works by a miracle
	if [[ "${desktop_dm}" == "lightdm" ]] && [ -n "$RealName" ]; then

		mkdir -p /etc/lightdm/lightdm.conf.d
		cat <<- EOF > /etc/lightdm/lightdm.conf.d/22-armbian-autologin.conf
			[Seat:*]
			autologin-user=$RealUserName
			autologin-user-timeout=0
			user-session=xfce
		EOF

		# select gnome session (has to be first or it breaks budgie/cinnamon desktop autologin and user-session)
		# @TODO: remove this, gnome should use gdm3, not lightdm
		[[ -x $(command -v gnome-session) ]] && sed -i "s/user-session.*/user-session=ubuntu/" /etc/lightdm/lightdm.conf.d/11-armbian.conf
		[[ -x $(command -v gnome-session) ]] && sed -i "s/user-session.*/user-session=ubuntu/" /etc/lightdm/lightdm.conf.d/22-armbian-autologin.conf

		# select awesome session
		[[ -x $(command -v awesome) ]] && sed -i "s/user-session.*/user-session=awesome/" /etc/lightdm/lightdm.conf.d/11-armbian.conf
		[[ -x $(command -v awesome) ]] && sed -i "s/user-session.*/user-session=awesome/" /etc/lightdm/lightdm.conf.d/22-armbian-autologin.conf

		# select budgie session
		[[ -x $(command -v budgie-desktop) ]] && sed -i "s/user-session.*/user-session=budgie-desktop/" /etc/lightdm/lightdm.conf.d/11-armbian.conf
		[[ -x $(command -v budgie-desktop) ]] && sed -i "s/user-session.*/user-session=budgie-desktop/" /etc/lightdm/lightdm.conf.d/22-armbian-autologin.conf

		# select cinnamon session
		[[ -x $(command -v cinnamon) ]] && sed -i "s/user-session.*/user-session=cinnamon/" /etc/lightdm/lightdm.conf.d/11-armbian.conf
		[[ -x $(command -v cinnamon) ]] && sed -i "s/user-session.*/user-session=cinnamon/" /etc/lightdm/lightdm.conf.d/22-armbian-autologin.conf

		# select deepin session
		[[ -x $(command -v deepin-wm) ]] && sed -i "s/user-session.*/user-session=deepin/" /etc/lightdm/lightdm.conf.d/11-armbian.conf
		[[ -x $(command -v deepin-wm) ]] && sed -i "s/user-session.*/user-session=deepin/" /etc/lightdm/lightdm.conf.d/22-armbian-autologin.conf

		# select ice-wm session
		[[ -x $(command -v icewm-session) ]] && sed -i "s/user-session.*/user-session=icewm-session/" /etc/lightdm/lightdm.conf.d/11-armbian.conf
		[[ -x $(command -v icewm-session) ]] && sed -i "s/user-session.*/user-session=icewm-session/" /etc/lightdm/lightdm.conf.d/22-armbian-autologin.conf

		# select i3 session
		[[ -x $(command -v i3) ]] && sed -i "s/user-session.*/user-session=i3/" /etc/lightdm/lightdm.conf.d/11-armbian.conf
		[[ -x $(command -v i3) ]] && sed -i "s/user-session.*/user-session=i3/" /etc/lightdm/lightdm.conf.d/22-armbian-autologin.conf

		# select lxde session
		[[ -x $(command -v startlxde) ]] && sed -i "s/user-session.*/user-session=LXDE/" /etc/lightdm/lightdm.conf.d/11-armbian.conf
		[[ -x $(command -v startlxde) ]] && sed -i "s/user-session.*/user-session=LXDE/" /etc/lightdm/lightdm.conf.d/22-armbian-autologin.conf

		# select lxqt session
		[[ -x $(command -v startlxqt) ]] && sed -i "s/user-session.*/user-session=lxqt/" /etc/lightdm/lightdm.conf.d/11-armbian.conf
		[[ -x $(command -v startlxqt) ]] && sed -i "s/user-session.*/user-session=lxqt/" /etc/lightdm/lightdm.conf.d/22-armbian-autologin.conf

		# select mate session
		[[ -x $(command -v mate-wm) ]] && sed -i "s/user-session.*/user-session=mate/" /etc/lightdm/lightdm.conf.d/11-armbian.conf
		[[ -x $(command -v mate-wm) ]] && sed -i "s/user-session.*/user-session=mate/" /etc/lightdm/lightdm.conf.d/22-armbian-autologin.conf

		# select sway wayland session
		[[ -x $(command -v sway) ]] && sed -i "s/user-session.*/user-session=sway/" /etc/lightdm/lightdm.conf.d/11-armbian.conf
		[[ -x $(command -v sway) ]] && sed -i "s/user-session.*/user-session=sway/" /etc/lightdm/lightdm.conf.d/22-armbian-autologin.conf

		# select xmonad session. The xmonad package ships two of them:
		# xmonad.desktop runs the window manager bare, while
		# gnome-flashback-xmonad.desktop runs it inside a GNOME Flashback
		# session and so gets a session dbus, a polkit agent and session
		# management. Prefer the latter when it can actually start -- its
		# TryExec is gnome-flashback, which comes from gnome-session-flashback
		# and is not always installed -- and fall back to the bare session.
		if [[ -x $(command -v xmonad) ]]; then
			xmonad_session="xmonad"
			if [[ -f /usr/share/xsessions/gnome-flashback-xmonad.desktop && -x $(command -v gnome-flashback) ]]; then
				xmonad_session="gnome-flashback-xmonad"
			fi
			sed -i "s/user-session.*/user-session=${xmonad_session}/" /etc/lightdm/lightdm.conf.d/11-armbian.conf
			sed -i "s/user-session.*/user-session=${xmonad_session}/" /etc/lightdm/lightdm.conf.d/22-armbian-autologin.conf
		fi

		ln -sf /lib/systemd/system/lightdm.service /etc/systemd/system/display-manager.service

		if [[ -f /var/run/resize2fs-reboot ]]; then
			# Let the user reboot now otherwise start desktop environment
			printf "\n\n\e[0;91mWarning: a reboot is needed to finish resizing the filesystem \x1B[0m \n"
			printf "\e[0;91mPlease reboot the system now \x1B[0m \n\n"
		else
			echo -e "\n\e[1m\e[39mNow starting desktop environment...\x1B[0m\n"
			sleep 1
			start_desktop lightdm
			if [ -f /root/.desktop_autologin ]; then
				rm /root/.desktop_autologin
			else
				systemctl -q enable armbian-disable-autologin.timer
				start_desktop armbian-disable-autologin.timer
			fi
			logout_console
		fi

	elif [[ "${desktop_dm}" == "gdm3" ]] && [ -n "$RealName" ]; then
		# 1st run goes without login
		mkdir -p /etc/gdm3
		cat <<- EOF > /etc/gdm3/custom.conf
			[daemon]
			AutomaticLoginEnable = true
			AutomaticLogin = $RealUserName
		EOF

		ln -sf /lib/systemd/system/gdm3.service /etc/systemd/system/display-manager.service

		if [[ -f /var/run/resize2fs-reboot ]]; then
			# Let the user reboot now otherwise start desktop environment
			printf "\n\n\e[0;91mWarning: a reboot is needed to finish resizing the filesystem \x1B[0m \n"
			printf "\e[0;91mPlease reboot the system now \x1B[0m \n\n"
		else
			echo -e "\n\e[1m\e[39mNow starting desktop environment...\x1B[0m\n"
			sleep 1
			start_desktop gdm3
			if [ -f /root/.desktop_autologin ]; then
				rm /root/.desktop_autologin
			else
				systemctl -q enable armbian-disable-autologin.timer
				start_desktop armbian-disable-autologin.timer
			fi
			logout_console
		fi
	elif [[ "${desktop_dm}" == "sddm" ]] && [ -n "$RealName" ]; then

		# create default sddm config
		mkdir -p /etc/sddm.conf.d

		if [ ! -e "/etc/sddm.conf.d/armbian.conf" ]; then
			cat <<- EOF > /etc/sddm.conf.d/armbian.conf
				[Theme]
				Current=breeze
				[General]
				InputMethod=none
			EOF
		fi

		# SDDM autologin needs a session. Themes without a user list (Omarchy)
		# log in as the last user, so set it too. Prefer omarchy.desktop.
		sddm_session=""
		for s in /usr/share/wayland-sessions/omarchy.desktop /usr/share/wayland-sessions/*.desktop /usr/share/xsessions/*.desktop; do
			if [[ -f "$s" ]]; then
				sddm_session=$(basename "$s")
				break
			fi
		done
		if [[ ! -s /var/lib/sddm/state.conf ]]; then
			mkdir -p /var/lib/sddm
			printf '[Last]\nUser=%s\nSession=%s\n' "$RealUserName" "$sddm_session" > /var/lib/sddm/state.conf
			chown sddm:sddm /var/lib/sddm/state.conf 2>/dev/null
		fi

		# 1st run goes without login
		cat <<- EOF > /etc/sddm.conf.d/autologin.conf
			[Autologin]
			User=$RealUserName
			Session=$sddm_session
		EOF
		echo -e "\n\e[1m\e[39mNow starting desktop environment via ${desktop_dm}...\x1B[0m\n"
		systemctl enable sddm 2>/dev/null
		start_desktop sddm

		if [ -f /root/.desktop_autologin ]; then
				rm /root/.desktop_autologin
		else
			systemctl -q enable armbian-disable-autologin.timer
		fi
		logout_console

	elif [[ "${desktop_dm}" == "cosmic-greeter" ]] && [ -n "$RealName" ]; then

		# 1st run goes without login. greetd runs [initial_session] once per boot.
		# The package config stays unchanged: a drop-in points greetd to a copy.
		{
			cat /etc/greetd/cosmic-greeter.toml
			printf '\n[initial_session]\ncommand = "start-cosmic"\nuser = "%s"\n' "$RealUserName"
		} > /etc/greetd/armbian-autologin.toml
		mkdir -p /etc/systemd/system/cosmic-greeter.service.d
		cat <<- EOF > /etc/systemd/system/cosmic-greeter.service.d/armbian-autologin.conf
			[Service]
			ExecStart=
			ExecStart=greetd --config /etc/greetd/armbian-autologin.toml
		EOF
		ln -sf /usr/lib/systemd/system/cosmic-greeter.service /etc/systemd/system/display-manager.service
		systemctl daemon-reload

		echo -e "\n\e[1m\e[39mNow starting desktop environment via ${desktop_dm}...\x1B[0m\n"
		start_desktop cosmic-greeter

		if [ -f /root/.desktop_autologin ]; then
			rm /root/.desktop_autologin
		else
			# Start it now: greetd would log in again at the next boot.
			systemctl -q enable armbian-disable-autologin.timer
			start_desktop armbian-disable-autologin.timer
		fi
		logout_console

	elif [[ "${desktop_dm}" == "cutefish-dm" ]] && [ -n "$RealName" ]; then

		# 1st run goes without login. The package does not ship this file.
		printf '[Autologin]\nUser=%s\nSession=cutefish-wayland\n' "$RealUserName" > /etc/cutefish-dm.conf
		# The package leaves the service disabled. --force takes the
		# display-manager.service alias from a different display manager.
		systemctl enable --force cutefish-dm 2>/dev/null

		echo -e "\n\e[1m\e[39mNow starting desktop environment via ${desktop_dm}...\x1B[0m\n"
		start_desktop cutefish-dm

		if [ -f /root/.desktop_autologin ]; then
			rm /root/.desktop_autologin
		else
			# Start it now: cutefish-dm would log in again at the next boot.
			systemctl -q enable armbian-disable-autologin.timer
			start_desktop armbian-disable-autologin.timer
		fi
		logout_console

	else
		# no display manager detected -> clear screen and show motd
		clear
		run-parts --lsbsysinit /etc/cron.daily
		run-parts --lsbsysinit /etc/update-motd.d

		# Display reboot recommendation if necessary
		if [[ -f /var/run/resize2fs-reboot ]]; then
			printf "\n\n\e[0;91mWarning: a reboot is needed to finish resizing the filesystem \x1B[0m \n"
			printf "\e[0;91mPlease reboot the system now \x1B[0m \n\n"
		fi

	fi
fi

# Run provisioning script if exists
if [[ -f /root/provisioning.sh ]]; then
	. /root/provisioning.sh
fi

# Marker cleanup is handled by _firstlogin_cleanup EXIT trap.
