#!/usr/bin/env bash
# .local/bin/garuda-locale.sh
#
# Detect the system keyboard configuration on first login,
# apply it to the normal Garuda Hyprland configuration,
# and then disable this script's startup command.

set -u

target="$HOME/.config/hypr/hyprland.lua"
map_file="/usr/share/systemd/kbd-model-map"

if [[ ! -f "$target" ]]; then
    echo "Error: Hyprland configuration file not found: $target" >&2
    exit 1
fi

keyboard_status=$(LC_ALL=C localectl --no-pager status 2>/dev/null || true)

get_keyboard_field() {
    local key=$1

    awk -v key="$key" '
        $0 ~ "^[[:space:]]*" key ":[[:space:]]*" {
            sub("^[[:space:]]*" key ":[[:space:]]*", "")
            print
            exit
        }
    ' <<< "$keyboard_status"
}

is_missing_keyboard_value() {
    [[ -z "${1:-}" ||
       "$1" == "(unset)" ||
       "$1" == "n/a" ||
       "$1" == "-" ]]
}

layout=$(get_keyboard_field "X11 Layout")
model=$(get_keyboard_field "X11 Model")
variant=$(get_keyboard_field "X11 Variant")
options=$(get_keyboard_field "X11 Options")

# If no XKB layout is configured, convert the virtual-console
# keymap through systemd's keyboard mapping table.
if is_missing_keyboard_value "$layout"; then
    vc_keymap=$(get_keyboard_field "VC Keymap")

    if ! is_missing_keyboard_value "$vc_keymap" &&
       [[ -r "$map_file" ]]; then

        map_line=$(
            awk -v key="$vc_keymap" '
                $1 == key {
                    print
                    exit
                }
            ' "$map_file"
        )

        if [[ -n "$map_line" ]]; then
            read -r _keymap layout model variant options _extra <<< "$map_line"
        fi
    fi
fi

# Final safe fallback.
if is_missing_keyboard_value "$layout"; then
    echo "Warning: no usable XKB keyboard layout was detected; using 'us'." >&2

    layout="us"
    model=""
    variant=""
    options=""
else
    is_missing_keyboard_value "$model"   && model=""
    is_missing_keyboard_value "$variant" && variant=""
    is_missing_keyboard_value "$options" && options=""
fi

# Do not modify the configuration unless all expected settings exist.
for key in kb_layout kb_variant kb_model kb_options; do
    if ! grep -Eq "^[[:space:]]*${key}[[:space:]]*=" "$target"; then
        echo "Error: could not find '$key' in $target" >&2
        exit 1
    fi
done

# Update all keyboard settings and disable this one-time startup
# command in a single modification.
sed -i -E \
    -e "s|^([[:space:]]*)kb_layout[[:space:]]*=.*|\1kb_layout  = \"$layout\",|" \
    -e "s|^([[:space:]]*)kb_variant[[:space:]]*=.*|\1kb_variant = \"$variant\",|" \
    -e "s|^([[:space:]]*)kb_model[[:space:]]*=.*|\1kb_model   = \"$model\",|" \
    -e "s|^([[:space:]]*)kb_options[[:space:]]*=.*|\1kb_options = \"$options\",|" \
    -e 's|^([[:space:]]*)hl\.exec_cmd\("\.local/bin/garuda-locale\.sh"\)[[:space:]]*$|\1-- hl.exec_cmd(".local/bin/garuda-locale.sh")|' \
    "$target"

# Reload only after the script has disabled its own startup command.
hyprctl reload >/dev/null 2>&1 || true

printf 'Garuda keyboard configuration applied:\n'
printf '  Layout : %s\n' "$layout"
printf '  Variant: %s\n' "${variant:-<none>}"
printf '  Model  : %s\n' "${model:-<none>}"
printf '  Options: %s\n' "${options:-<none>}"
