There are three components to the solution that would let you swap keyboard layouts:
- Detect when the keyboard is plugged in/out
- Detect the layout on the keyboard
- Set the layout of your system to match the keyboard layout.
1. Detect when the keyboard is plugged in/out
All hardware changes are sent on the D-Bus message bus daemon.
D-Bus is a message bus system, a simple way for applications to talk to one another. In addition to interprocess communication, D-Bus helps coordinate process lifecycle; it makes it simple and reliable to code a "single instance" application or daemon, and to launch applications and daemons on demand when their services are needed.
D-Bus supplies both a system daemon (for events such as "new hardware device added" or "printer queue changed") and a per-user-login-session daemon (for general IPC needs among user applications).
You can monitor the events sent on the D-Bus via the dbus-monitor command:
dbus-monitor --system #show all events
dbus-monitor --system --profile 'interface=org.freedesktop.Hal.Manager' # filter: only events sent by Hal
dbus-monitor --system --profile 'interface=org.freedesktop.Hal.Manager, member=DeviceAdded' # filter: only DeviceAdded events sent by Hal
Plug in your keyboard, and watch the messages go by. That should give you an idea of the filter you need to detect a keyboard being plugged in or out. You'll also need to get familiar with the dbus-monitor usage in more detail.
2. Detect the layout of the keyboard
Once the keyboard is plugged into the system, HAL(Hardware Abstraction Layer) configures it. You can retrieve this info using the hal-get-property command once you have identified the key you need. For example, on my system:
$ hal-get-property --udi /org/freedesktop/Hal/devices/platform_i8042_i8042_KBD_port_logicaldev_input --key "input.xkb.layout"
gb
$ hal-get-property --udi /org/freedesktop/Hal/devices/platform_i8042_i8042_KBD_port_logicaldev_input --key "input.xkb.model"
pc105
Look at this answer for a detailed explanation of how to get values from HAL: setting up process profiles on ubuntu. I think the D-Bus message might give you the configured HAL node for the connected device, but I'm not certain. If not, you know that it will be in either of two places - corresponding to one of two keyboards.
3. Select the layout of your system to match the keyboard layout
joe already pointed out how you can do this using xmodmap.