#!/bin/sh

. /usr/lib/live/config.sh

## live-config(7) - System Configuration Components
## Copyright (C) 2026 The Debian Live team
##
## This program comes with ABSOLUTELY NO WARRANTY; for details see COPYING.
## This is free software, and you are welcome to redistribute it
## under certain conditions; see COPYING for details.


#set -e

Cmdline ()
{
	# Reading kernel command line
	for _PARAMETER in ${LIVE_CONFIG_CMDLINE}
	do
		case "${_PARAMETER}" in
			live-config.username=*|username=*)
				LIVE_USERNAME="${_PARAMETER#*username=}"
				;;
			live-config.keyboard-layouts=*|keyboard-layouts=*)
				LIVE_KEYBOARD_LAYOUTS="${_PARAMETER#*keyboard-layouts=}"
				;;
		esac
	done
}

Init ()
{
	# Checking if package is installed or already configured
	if ! pkg_is_installed "lomiri-keyboard"
	then
		exit 0
	fi

	if component_was_executed "lomiri-keyboard"
	then
		exit 0
	fi

	echo -n " lomiri-keyboard"
}

Config ()
{
	# Note: this assumes that only ONE layout is configured on the kernel command line
	# If more are provided, it won't work in a spectacular way :-)
	if [ -n "${LIVE_KEYBOARD_LAYOUTS}" ]
	then
		# Register the keyboard in the list of OSK languages
		sudo -u "${LIVE_USERNAME}" dbus-run-session -- gsettings set com.lomiri.keyboard.maliit enabled-languages "['${LIVE_KEYBOARD_LAYOUTS}', 'emoji']"
		# Set the active language of the OSK
		sudo -u "${LIVE_USERNAME}" dbus-run-session -- gsettings set com.lomiri.keyboard.maliit active-language "'${LIVE_KEYBOARD_LAYOUTS}'"
		# Register the keyboard layout for the external keyboard
		sudo -u "${LIVE_USERNAME}" dbus-run-session -- gsettings set org.gnome.desktop.input-sources sources "[('xkb', '${LIVE_KEYBOARD_LAYOUTS}')]"
		# Activate the keyboard in the terminal app
		cat << EOF >> /var/lib/AccountsService/users/${LIVE_USERNAME}
[com.lomiri.shell.AccountsService]
InputSources=[{'xkb': '${LIVE_KEYBOARD_LAYOUTS}'}]
EOF
	fi
	# Creating state file
	touch /var/lib/live/config/lomiri-keyboard
}

Cmdline
Init
Config
