#!/bin/sh
# Automatically detect or generate the XKB variables corresponding to the
# configured vconsole keymap set by the system installer

vconsole="/etc/vconsole.conf"

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

xkb_layout="$(grep -Po '(?<=XKBLAYOUT=).*' $vconsole)"
xkb_options="$(grep -Po '(?<=XKBOPTIONS=).*' $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 XBD layout by converting the existing keymap (man 1 localectl)
      localectl set-keymap "$keymap"
      # Try to extract the XBD 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

# Generate the openSUSEway keyboard configuration file
cat << EOF
# Set keyboard layout based on system setup
# Generated by openSUSEway $0 during installation
input "type:keyboard" {
  xkb_layout $xkb_layout
EOF
# The xkb_options are optional
if [ -n "$xkb_options" ]; then
  echo "  xkb_options $xkb_options"
fi
echo "}"
