#!/bin/sh
# Verify that the KWin Zones plugin can actually be loaded by the installed
# KWin: start a headless kwin_wayland and check that the xx_zone_manager_v1
# Wayland global is advertised to clients.
set -eu

# Unix socket paths are limited to ~108 bytes, so use a short runtime
# directory instead of the possibly deeply nested AUTOPKGTEST_TMP.
RT=$(mktemp -d /tmp/kwin-zones-test.XXXXXX)
trap 'rm -rf "$RT"' EXIT
export RT

export XDG_RUNTIME_DIR="$RT"
export XDG_CONFIG_HOME="$RT/config"
export XDG_DATA_HOME="$RT/data"
export XDG_CACHE_HOME="$RT/cache"
unset DISPLAY WAYLAND_DISPLAY DBUS_SESSION_BUS_ADDRESS

# This runs as the "session" process inside KWin, which exits once it is done.
# Plugins are loaded shortly after KWin has started accepting connections, so
# poll for the global for a while instead of checking only once.
cat > "$RT/probe.sh" <<'PROBE'
#!/bin/sh
i=0
while [ $i -lt 120 ]; do
    wayland-info > "$RT/wayland-info.out" 2>&1 || true
    if grep -q "'xx_zone_manager_v1'" "$RT/wayland-info.out"; then
        touch "$RT/found"
        exit 0
    fi
    sleep 0.5
    i=$((i + 1))
done
exit 1
PROBE
chmod +x "$RT/probe.sh"

timeout 180 dbus-run-session -- \
    kwin_wayland --virtual --no-lockscreen --no-global-shortcuts \
        --socket wayland-kwin-zones-test \
        --exit-with-session "$RT/probe.sh" > "$RT/kwin.log" 2>&1 || true

if [ -e "$RT/found" ]; then
    echo "OK: xx_zone_manager_v1 global is advertised, KWin Zones plugin is loaded."
    exit 0
fi

echo "FAIL: xx_zone_manager_v1 global not found, KWin Zones plugin was not loaded." >&2
echo "--- kwin_wayland output:" >&2
cat "$RT/kwin.log" >&2
echo "--- wayland-info output:" >&2
grep "^interface:" "$RT/wayland-info.out" >&2 2>/dev/null || true
exit 1
