# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Copyright 2015-2022 SUSE LLC

menulist()
{
	list=()
	local line
	while read line; do
		list+=("$line" '')
	done < <("$@"||true)
	[ -n "$list" ]
}

dialog_locale()
{
        default="en_US"
        [ -f /etc/locale.conf ] && locale_lang="$(awk -F= '$1 == "LANG" { split($2,fs,"."); print fs[1]; exit }' /etc/locale.conf)"
        [ -n "$locale_lang" ] && default="$locale_lang"

        list=() # Set by findlocales
        newlocale="$default"
        if ! findlocales; then
                d --msgbox $"No locales found" 0 0
        elif [ "${#list[@]}" -eq 2 ]; then # Only a single entry
                newlocale="${list[0]}"
        else
                d --default-item "$default" --menu $"Select system locale" 0 0 "$(menuheight ${#list[@]})" "${list[@]}"
                newlocale="${result}"
        fi

        JEOS_LOCALE="${newlocale}.UTF-8"
}

dialog_keytable()
{
        default="us"
        [ -f /etc/vconsole.conf ] && vconsole_keymap="$(awk -F= '$1 == "KEYMAP" { split($2,fs,"."); print fs[1]; exit }' /etc/vconsole.conf)"
        [ -n "$vconsole_keymap" ] && default="$vconsole_keymap"

        if findkeymaps \
                && d --default-item "$default" --menu  $"Select keyboard layout" 0 0 "$(menuheight ${#list[@]})" "${list[@]}"; then
                if [ -n "$result" ]; then
                        JEOS_KEYTABLE="$result"
                fi
        else
                d --msgbox $"Error setting keyboard" 5 26
        fi
}

dialog_timezone()
{
	default="$(readlink -f /etc/localtime)"
	default="${default##/usr/share/zoneinfo/}"
	# timedatectl doesn't work as dbus is not up yet
	# menulist timedatectl --no-pager list-timezones
	if menulist awk \
		'BEGIN{print "UTC"; sort="sort"}/^#/{next;}{print $3|sort}END{close(sort)}' \
		/usr/share/zoneinfo/zone.tab \
		&& d --default-item "$default" --menu $"Select time zone" 0 0 "$(menuheight ${#list[@]})" "${list[@]}"; then
			if [ -n "$result" ]; then
				JEOS_TIMEZONE="$result"
			fi
	else
		d --msgbox $"Error setting timezone" 5 26
	fi
}

dialog_password()
{
	while true; do
		d --insecure --passwordbox  $"Enter root password" 0 0
		password="$result"
		d --insecure --passwordbox  $"Confirm root password" 0 0
		if [ "$password" != "$result" ]; then
			d --msgbox $"Entered passwords don't match" 5 40
			continue
		fi
		if [ -z "$password" ]; then
			warn $"Warning: No root password set.

You cannot log in that way. A debug shell will be started on tty9 just this time. Use it to e.g. import your ssh key." || true
		run systemctl start debug-shell.service
		fi
		break
	done
}

# vim: syntax=sh
