#!/bin/bash
# The launcher order, read off the screen, with real windows opening and
# closing underneath it.
#
# 0.2.4 shipped a launcher order that was right in every configuration
# test and wrong on the bar, so this test opens actual applications and
# looks at actual pixels. Run with a classroom session already up:
#
#     tools/lab/lab session
#     tools/lab/order-check
set -uo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
NAME="${LAB_NAME:-classroom-v2-lab}"
WANT="wonderink browser player"

passed=0
failed=0

# Consecutive repeats are collapsed before comparing. The classroom sets
# groupingStrategy=0 on purpose — every window gets its own button, so a
# teacher never has to open a group to discover a second window exists —
# so two browser windows are two browser buttons and that is correct. What
# must not change is the order of the KINDS: Wonder Ink, then the browser,
# then the player.
check() {
    local label="$1"
    local got
    got="$("$ROOT/tools/lab/panel-order" | uniq | tr '\n' ' ' | sed 's/ *$//')"

    if [[ "$got" == "$WANT" ]]; then
        echo "  ok   $label"
        passed=$((passed + 1))
    else
        echo "  FAIL $label"
        echo "       wanted [$WANT]"
        echo "       got    [$got]"
        failed=$((failed + 1))
    fi
}

app() {
    docker exec -d -u classroom \
        -e XDG_RUNTIME_DIR=/run/user/1000 -e WAYLAND_DISPLAY=wayland-0 \
        -e HOME=/home/classroom -e XDG_CURRENT_DESKTOP=KDE \
        -e DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus \
        "$NAME" sh -c "$1"
}

echo "1. nothing running"
docker exec "$NAME" pkill -u classroom chrome >/dev/null 2>&1 || true
sleep 4
check "the bar is Wonder Ink, the browser, the player"

echo "2. the browser opens"
app 'exec google-chrome --ozone-platform=wayland --no-sandbox --disable-gpu --no-first-run about:blank'
sleep 16
check "the browser stays in its place and does not move behind the player"

echo "3. a second browser window"
app 'exec google-chrome --ozone-platform=wayland --no-sandbox --disable-gpu --new-window about:blank'
sleep 12
check "a second window adds a button beside it and moves nothing"

echo "4. Wonder Ink opens as well, with the browser still running"
app 'exec classroom-wonderink'
sleep 18
check "the first launcher does not move when it is the one that opens"

echo "5. Wonder Ink closes, the browser stays"
docker exec "$NAME" pkill -u classroom -f classroom-wonderink >/dev/null 2>&1 || true
sleep 6
check "closing the middle of three changes nothing"

echo "6. the browser closes again"
docker exec "$NAME" pkill -u classroom chrome >/dev/null 2>&1 || true
sleep 6
check "closing it puts nothing back in a different order"

echo
echo "$passed passed, $failed failed"
[[ $failed -eq 0 ]]
