#!/bin/dash
#
# Apply X11 keyboard layout via setxkbmap when an evdev keyboard is added.
# Layout comes from /etc/default/keyboard (same source as input.sh metadata).
# Requires an active X11 socket under /tmp/.X11-unix/; no-op otherwise.

set -u

. "$VDEV_HELPERS/subr.sh"

xkb_setlayout_for_user() {
	_display="$1"
	_user="$2"
	_home="$3"
	_args="$4"
	_setxkbmap="$5"
	_auth=""

	if [ -f "$_home/.Xauthority" ]; then
		_auth="$_home/.Xauthority"
	elif [ -n "${XAUTHORITY:-}" ] && [ -f "$XAUTHORITY" ]; then
		_auth="$XAUTHORITY"
	fi

	if [ -n "$_auth" ]; then
		su - "$_user" -s /bin/sh -c \
			"DISPLAY='$_display' XAUTHORITY='$_auth' '$_setxkbmap' $_args" \
			>/dev/null 2>&1
	else
		su - "$_user" -s /bin/sh -c \
			"DISPLAY='$_display' '$_setxkbmap' $_args" \
			>/dev/null 2>&1
	fi
}

main() {
	local _setxkbmap _args _sock _display _user _home _input_data _rc

	if [ "${VDEV_ACTION:-}" != "add" ]; then
		return 0
	fi

	case "${VDEV_PATH:-}" in
	input/event*) ;;
	*) return 0 ;;
	esac

	if [ -x /usr/bin/setxkbmap ]; then
		_setxkbmap=/usr/bin/setxkbmap
	elif [ -x /usr/bin/X11/setxkbmap ]; then
		_setxkbmap=/usr/bin/X11/setxkbmap
	else
		return 0
	fi

	_input_data="$("$VDEV_HELPERS/stat_input" "${VDEV_MOUNTPOINT:-/dev}/${VDEV_PATH}")"
	_rc=$?
	if [ "$_rc" -ne 0 ]; then
		vdev_warn "xkb-setlayout: stat_input ${VDEV_PATH} exit $_rc"
		return 0
	fi
	eval "$_input_data"

	if [ -z "${VDEV_INPUT_KEY:-}" ] && [ -z "${VDEV_INPUT_KEYBOARD:-}" ]; then
		return 0
	fi

	if [ ! -f /etc/default/keyboard ]; then
		vdev_log "xkb-setlayout: /etc/default/keyboard missing; skip"
		return 0
	fi

	# shellcheck disable=SC1091
	. /etc/default/keyboard

	_args=""
	[ -n "${XKBMODEL:-}" ] && _args="$_args -model $XKBMODEL"
	[ -n "${XKBLAYOUT:-}" ] && _args="$_args -layout $XKBLAYOUT"
	[ -n "${XKBVARIANT:-}" ] && _args="$_args -variant $XKBVARIANT"
	[ -n "${XKBOPTIONS:-}" ] && _args="$_args -option $XKBOPTIONS"
	[ -n "$_args" ] || return 0

	for _sock in /tmp/.X11-unix/X[0-9]*; do
		[ -e "$_sock" ] || continue
		_display=":${_sock#/tmp/.X11-unix/X}"
		_user="$(stat -c '%U' "$_sock" 2>/dev/null)" || continue
		[ "$_user" != "root" ] || continue
		_home="$(getent passwd "$_user" | cut -d: -f6)" || continue
		[ -n "$_home" ] || continue
		xkb_setlayout_for_user "$_display" "$_user" "$_home" "$_args" "$_setxkbmap"
	done

	return 0
}

if [ "${VDEV_DAEMONLET:-0}" -eq 0 ]; then
	main
	exit $?
fi
