#!/bin/bash
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Copyright 2015-2022 SUSE LLC

jeos_prefix="$(realpath "$(dirname "${BASH_SOURCE[0]}")/../")"

# shellcheck source-path=SCRIPTDIR/../
. "${jeos_prefix}/share/jeos-firstboot/jeos-firstboot-functions"
# shellcheck source-path=SCRIPTDIR/../
. "${jeos_prefix}/share/jeos-firstboot/jeos-firstboot-dialogs"

# for testing we may run as non root
if [ -w /run ]; then
	export TMPDIR=/run
	# debugging
	if [ -n "$FIRSTBOOT_DEBUG" ]; then
		set -x
		exec 2>/var/log/firstboot-debug
	fi
else
	dry=1
fi

if [ -n "$dry" ]; then
	run() {
		echo "$@"
	}
else
	run() {
		"$@"
	}
fi

cleanup() {
	#call_module_hook cleanup
	echo
}
trap cleanup EXIT

init_modules

# Get a list of all config modules
config_modules=()
for module in "${modules[@]}"; do
	if module_has_hook "$module" "jeos_config"; then
		config_modules+=("${module}")
	fi
done

select_config()
{
	local modules_order=("locale" $"Locale" "keytable" $"Keyboard Layout" "timezone" $"Timezone" "password" $"Password")
	for module in "${config_modules[@]}"; do
		modules_order+=("$module" "$(module_get_prop "${module}" "title" "${module}")")
	done

	d_with_result --no-tags --menu $"Select configuration module" 0 0 "$(menuheight ${#modules_order[@]})" "${modules_order[@]}" || exit 0
}

usage()
{
cat <<EOF
Usage: jeos-config [OPTION...] [CONFIG_NAME]
Configure system settings using an interactive dialog

	-h		shows this usage help
	locale		Show configuration for locale
	keytable	Show configuration for keyboard
	timezone	Show configuration for timezone
	password	Show configuration for password
EOF
	for module in "${config_modules[@]}"; do
		local fallbackdescription="$(printf $"Show configuration for %s" "${module}")"
		printf "\t%-8s\t%s\n" "${module}" "$(module_get_prop "$module" "description" "$fallbackdescription")"
	done
}

while getopts ":h" opt; do
	case ${opt} in
		h) 
			usage
			exit 0
			;;
		\?) 
			echo "Invalid Option: -$OPTARG" 1>&2
			usage
			exit 1
			;;
	esac
done

if [ ${OPTIND} -gt $# ]; then
	select_config
	subcommand=${result}
else
	subcommand=${!OPTIND}; shift
fi

case "$subcommand" in
	locale)
		list=() # Set by findlocales
		if ! findlocales; then
			d --msgbox $"No locales found" 0 0
		elif [ "${#list[@]}" -eq 2 ]; then # Only a single entry
			d --msgbox $"Locale set to ${list[0]}, no more locales available" 5 50
		else
			dialog_locale
			apply_locale
		fi
		;;
	keytable)
		dialog_keytable
		JEOS_LOCALE="$(get_current_locale)"
		apply_locale_and_keytable
		;;	
	timezone)
		dialog_timezone
		timedatectl set-timezone "$JEOS_TIMEZONE"
		;;	
	password)
		dialog_password
		apply_password
		;;
	*)
		call_module "$subcommand" "jeos_config" || echo "Unknown option '$subcommand'"
esac
