#!/bin/bash
# Filename:      grml-lang
# Purpose:       load keyboard layout
# Authors:       grml-team (grml.org), (c) Michael Prokop <mika@grml.org>
# Bug-Reports:   see http://grml.org/bugs/
# License:       This file is licensed under the GPL v2.
################################################################################

CONFFILE=/etc/default/keyboard
PN="$(basename "$0")"

# shellcheck disable=SC1091
. /etc/grml/lsb-functions

usage(){
    echo "Usage: ${PN} <language>"
    echo "supported values: at, ch, de, dvorak, en, es, fr, hu, it, jp, uk, us"
}

# Update keyboard configuration and apply changes
configure_keyboard(){
  sudo tee "$CONFFILE" > /dev/null <<EOF
# Keyboard configuration, written by grml-lang.
XKBMODEL="pc105"
XKBLAYOUT="$XKBLAYOUT"
XKBVARIANT="$XKBVARIANT"
XKBOPTIONS="$XKBOPTIONS"
EOF

  # Apply keyboard changes immediately:
  # Let setupcon update the files /etc/console-setup/cached*. It will also try
  # to activate the new configuration.
  sudo setupcon --force --save
  # However, due to an apparenty loadkeys or kernel limitation, when the current
  # screen is managed by X11, loadkeys *without* -u fails or does nothing. Force
  # loading the keymap for the linux virtual consoles.
  sudo loadkeys -u /etc/console-setup/cached_UTF-8_del.kmap.gz
  # Trigger udev rules for input devices. If X11 is installed, this will make
  # udev pick up /etc/default/keyboard, and X11 will pick up the keymap from udev.
  sudo udevadm trigger --subsystem-match=input --action=change
}

if [ $# -lt "1" ] ; then
   usage >&2
   exit 1
fi

LANGUAGE="$1"

# shellcheck disable=SC1091
. /usr/share/grml-autoconfig/language-functions

# Check if we found a valid keyboard configuration
if [ -z "$XKBLAYOUT" ] ; then
  echo "E: No valid language given."
  echo
  usage
  echo
  echo "Notice: grml-lang now configures keyboard layout via /etc/default/keyboard."
  echo "For locale settings, use grml-setlang."
  exit 1
fi

configure_keyboard

eindent
new_layout="$XKBLAYOUT"
if [ -n "$XKBVARIANT" ] && [ "$XKBVARIANT" != "," ]; then
  new_layout="$new_layout $XKBVARIANT"
fi
einfo "Configured Keyboard Layout: $new_layout."
eend 0

## END OF FILE #################################################################
