#!/bin/bash

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

set -o errexit
set -o nounset
set -o errtrace
set -o pipefail

command -v stcat >/dev/null
command -v pager >/dev/null

use_pager='true'

while [ -n "${1:-}" ]; do
   case "$1" in
   '--no-pager')
      use_pager='false'
      shift
      ;;
   '--')
      shift
      break
      ;;
   *)
      break
      ;;
   esac
done

args=( "$@" )
subcommand="${args[0]:-}"

if [ -z "${subcommand}" ]; then
  printf '%s\n' "$0: ERROR: Missing command (expected: list-x11-keymap-layouts|list-x11-keymap-variants|list-x11-keymap-options)"
  exit 1
fi

helper_scripts_share_dir='/usr/share/helper-scripts'
layouts_static_file="${helper_scripts_share_dir}/localectl-list-x11-keymap-layouts-static.txt"
variants_static_dir="${helper_scripts_share_dir}/localectl-list-x11-keymap-variants-static.d"
options_static_file="${helper_scripts_share_dir}/localectl-list-x11-keymap-options-static.txt"

if [ "${subcommand}" = "list-x11-keymap-layouts" ]; then
  if [ "$use_pager" = 'true' ]; then
    stcat "${layouts_static_file}" | pager
  else
    stcat "${layouts_static_file}"
  fi
elif [ "${subcommand}" = "list-x11-keymap-variants" ]; then
  if [ -z "${args[1]:-}" ]; then
    printf '%s\n' "$0: ERROR: Missing layout argument!"
    exit 1
  fi
  if ! [ -d "${variants_static_dir}" ]; then
    printf '%s\n' "$0: ERROR: Folder variants_static_dir '${variants_static_dir}' missing! args[1]: '${args[1]}'!"
    exit 1
  fi
  if ! [ -f "${variants_static_dir}/${args[1]}" ]; then
    printf '%s\n' "$0: ERROR: Unrecognized keymap '${args[1]}'!"
    exit 1
  fi
  if [ "$use_pager" = 'true' ]; then
    stcat "${variants_static_dir}/${args[1]}" | pager
  else
    stcat "${variants_static_dir}/${args[1]}"
  fi
elif [ "${subcommand}" = "list-x11-keymap-options" ]; then
  if [ "$use_pager" = 'true' ]; then
    stcat "${options_static_file}" | pager
  else
    stcat "${options_static_file}"
  fi
else
  printf '%s\n' "$0: ERROR: Unknown command: '${args[*]}'"
  exit 1
fi
