#!/usr/bin/env bash
# Keyboard layout, as a flag.
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
# Licensed under the GNU General Public License v2 only.
#
# waybar's hyprland/language module styles as #language and nothing else: it
# has no per-language CSS class, so a flag cannot be selected by a selector.
# format-<lang> exists but takes text, not a path. So the flag arrives the
# same way every other icon on this bar does, through an `image` module.
#
#     wb-lang        # print "$path\n$tooltip" for the image module
#
# The flags live next to this bar's config because the icon theme ships 13 and
# neither Italian nor British is among them.
set -euo pipefail

flags="$HOME/.config/waybar-udt"

# hyprctl names the layout in full ("Italian", "English (US)"), which is what
# the keymap reports; match on that rather than on the short code, because the
# short code is not in this output.
layout="$(hyprctl devices -j 2>/dev/null \
    | python3 -c 'import json,sys
try:
    d = json.load(sys.stdin)
except Exception:
    sys.exit(0)
for k in d.get("keyboards", []):
    if k.get("name") == "2.4g-dongle":
        print(k.get("active_keymap", ""))
        break' 2>/dev/null || true)"

case "$layout" in
Italian*) flag="flag-it.svg"; name="Italian" ;;
English*) flag="flag-gb.svg"; name="English" ;;
"")       flag="flag-it.svg"; name="unknown" ;;
*)        flag="flag-gb.svg"; name="$layout" ;;
esac

if [[ ! -r "$flags/$flag" ]]; then
	echo "wb-lang: missing $flags/$flag" >&2
	exit 1
fi

echo "$flags/$flag"
echo "Layout: $name"
