#!/bin/sh
#
# Copyright (c) 2025 SUSE LLC and contributors
#
# Author: Filippo Bonazzi <filippo.bonazzi@suse.com>
#
# Generate a Sway keyboard configuration block with the xkb_* options
# corresponding to the XKB* variables found in /etc/vconsole.conf
#
# The XKBLAYOUT variable is required. If not found in /etc/vconsole.conf,
# generate it by converting the configured vconsole keymap set by the system
# installer.
#
# See also: man 5 sway-input, man 7 xkeyboard-config, man 1 localectl

vconsole="/etc/vconsole.conf"

###############################################################################

# Extract the required XKB layout variable
xkb_layout="$(grep -Po '(?<=XKBLAYOUT=).*' $vconsole)"

# Generate the XKB layout if empty
if [ -z "$xkb_layout" ]; then
    keymap="$(grep -Po '(?<=KEYMAP=).*' $vconsole)"

    if [ -z "$keymap" ]; then
      echo "fatal: no xkb layout or keymap found" >&2
      exit 1
    else
      cp "$vconsole" "${vconsole}.bak"
      # Set the XKB layout by converting the existing keymap
      localectl set-keymap "$keymap"
      # Try to extract the XKB layout again
      xkb_layout="$(grep -Po '(?<=XKBLAYOUT=).*' $vconsole)"
      if [ -z "$xkb_layout" ]; then
        echo "fatal: could not generate xkb layout from keymap" >&2
        exit 2
      fi
    fi
fi

# Extract the other optional XKB variables
xkb_model="$(grep -Po '(?<=XKBMODEL=).*' $vconsole)"
xkb_options="$(grep -Po '(?<=XKBOPTIONS=).*' $vconsole)"
xkb_variant="$(grep -Po '(?<=XKBVARIANT=).*' $vconsole)"

# Generate a Sway keyboard configuration block containing the required and
# optional variables
cat << EOF
# Set keyboard layout based on system setup
# Generated by $0 during installation
input "type:keyboard" {
  xkb_layout $xkb_layout
EOF
if [ -n "$xkb_model" ]; then
  echo "  xkb_model $xkb_model"
fi
if [ -n "$xkb_options" ]; then
  echo "  xkb_options $xkb_options"
fi
if [ -n "$xkb_variant" ]; then
  echo "  xkb_variant $xkb_variant"
fi
echo "}"
