#!/bin/sh

## Copyright (c) 2019 - 2025 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

#set -x

true "usability-misc $0: START"

set -e

if ! [ -d /boot/grub/kb_layouts ]; then
  exit 0
fi

printf '%s\n' "\
function load_kb_layout {
  kb_layout_name=\"\$1\"

  if [ x\$kb_layout_name = x ]; then
    echo \"No keyboard layout specified! Press 'Enter' to continue.\"
    read
    return 1
  fi

  if ! [ -f \"\${prefix}/kb_layouts/\${kb_layout_name}.gkb\" ]; then
    echo \"Keyboard layout '\$kb_layout_name' does not exist! Press 'Enter' to continue.\"
    read
    return 1
  fi

  echo \"Switching keyboard layouts may cause the keyboard to malfunction or\"
  echo \"become unresponsive. If this occurs, force-reboot the machine to\"
  echo \"fix this.\"
  echo
  if ! terminal_input at_keyboard; then
    echo \"Could not enable at_keyboard driver! Press 'Enter' to continue.\"
    read
    return 1
  fi

  if ! keymap \"\${prefix}/kb_layouts/\${kb_layout_name}.gkb\"; then
    echo \"Could not load keyboard layout '\$kb_layout_name'! Press 'Enter' to continue.\"
    read
    return 1
  fi

  echo \"Keyboard layout '\$kb_layout_name' loaded. Press 'Enter' to continue.\"
  read
  return 0
}

submenu 'Keyboard layout options' \$menuentry_id_option 'kb-layout-options' {"

if [ -f /boot/grub/kb_layouts/user-layout.gkb ]; then
  if [ -f /boot/grub/kb_layouts/user-layout.name ]; then
    user_layout_name="$(cat /boot/grub/kb_layouts/user-layout.name)" || { user_layout_name='unknown'; true; }
  else
    user_layout_name='unknown'
  fi

  printf '%s\n' "\
  menuentry \"SWITCH to user-defined keyboard layout '$user_layout_name'\" \$menuentry_id_option 'switch-kb-layout-user-defined' {
    load_kb_layout 'user-layout'
  }"
fi

for layout_file in /boot/grub/kb_layouts/*.gkb; do
  if ! [ -f "$layout_file" ]; then
    continue
  fi
  if [ "$layout_file" = '/boot/grub/kb_layouts/user-layout.gkb' ]; then
    continue
  fi
  layout_name="$(basename "$layout_file" | sed 's/\..*//')"
  printf '%s\n' "\
  menuentry \"SWITCH to layout '$layout_name'\" \$menuentry_id_option 'switch-kb-layout-$layout_name' {
    load_kb_layout '$layout_name'
  }"
done

printf '%s\n' "\
}
"

true "usability-misc $0: END"
