#!/bin/bash
set -euo pipefail

CURRENT=$(grep '^XKBLAYOUT=' /etc/default/keyboard 2>/dev/null | cut -d'"' -f2 || echo "us")

LAYOUT=$(whiptail --title "Keyboard Layout" \
    --menu "Current layout: $CURRENT\n\nSelect a new layout:" 20 50 11 \
    "us" "US English" \
    "no" "Norwegian" \
    "gb" "UK English" \
    "se" "Swedish" \
    "dk" "Danish" \
    "fi" "Finnish" \
    "de" "German" \
    "fr" "French" \
    "nl" "Dutch" \
    "es" "Spanish" \
    "it" "Italian" \
    3>&1 1>&2 2>&3) || exit 0

if [ "$LAYOUT" = "$CURRENT" ]; then
    whiptail --title "Keyboard Layout" --msgbox "Already set to: $LAYOUT" 8 40
    exit 0
fi

sudo tee /etc/default/keyboard > /dev/null <<EOF
XKBMODEL="pc105"
XKBLAYOUT="$LAYOUT"
XKBVARIANT=""
XKBOPTIONS=""
BACKSPACE="guess"
EOF
setupcon --force 2>/dev/null || true
sudo loadkeys "$LAYOUT" 2>/dev/null || true
swaymsg input type:keyboard xkb_layout "$LAYOUT" 2>/dev/null || true
whiptail --title "Keyboard Layout" --msgbox "Layout changed to: $LAYOUT" 8 40