#!/bin/bash
# Every recovery property the classroom depends on, measured against the
# lab as the package built it. Run after tools/lab/from-package.
set -uo pipefail

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

inlab() { docker exec "$NAME" "$@"; }
insession() {
    docker exec -u classroom -e XDG_RUNTIME_DIR=/run/user/1000 \
        -e DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus \
        -e HOME=/home/classroom "$NAME" "$@"
}

kill_and_wait() {
    local proc="$1" rounds="${2:-1}" gap="${3:-1}"
    for round in $(seq 1 "$rounds"); do
        local old new started
        old=$(inlab pgrep -x "$proc" | head -1)
        [ -n "$old" ] || { echo "  $proc was not running"; return 1; }
        started=$(date +%s%N)
        inlab kill -9 "$old" 2>/dev/null
        new=""
        while [ $(( ($(date +%s%N) - started) / 1000000000 )) -lt 60 ]; do
            new=$(inlab pgrep -x "$proc" | head -1)
            [ -n "$new" ] && [ "$new" != "$old" ] && break
            sleep 0.25
        done
        if [ -n "$new" ] && [ "$new" != "$old" ]; then
            printf "  %-16s round %s: back in %ss\n" "$proc" "$round" \
                "$(awk "BEGIN{printf \"%.1f\", ($(date +%s%N)-$started)/1000000000}")"
        else
            printf "  %-16s round %s: DID NOT COME BACK\n" "$proc" "$round"
            return 1
        fi
        sleep "$gap"
    done
}

echo "the panel, killed eight times a second apart"
kill_and_wait plasmashell 8 1

echo
echo "the compositor, killed twice"
kill_and_wait kwin_wayland 2 4

echo
echo "the audio policy, killed three times"
for round in 1 2 3; do
    inlab pkill -9 -f "bin/classroom-audio" 2>/dev/null
    sleep 6
    printf "  audio round %s: %s\n" "$round" \
        "$(insession systemctl --user is-active ekklesia-classroom-audio.service)"
done

echo
echo "Parent Call, killed while the panel is watched"
insession sh -c 'setsid /usr/local/bin/classroom-parent-call >/dev/null 2>&1 &'
sleep 5
before=$(inlab pgrep -c -x plasmashell)
inlab pkill -9 -f "bin/classroom-parent-call" 2>/dev/null
sleep 3
printf "  panel before %s, after %s\n" "$before" "$(inlab pgrep -c -x plasmashell)"

echo
echo "the browser, killed while the panel is watched"
insession sh -c 'setsid /usr/local/bin/classroom-browser >/dev/null 2>&1 &'
sleep 18
before=$(inlab pgrep -c -x plasmashell)
inlab pkill -9 chrome 2>/dev/null
sleep 4
printf "  panel before %s, after %s\n" "$before" "$(inlab pgrep -c -x plasmashell)"

echo
echo "what is still standing"
printf "  plasmashell=%s kwin=%s applets=%s audio=%s\n" \
    "$(inlab pgrep -c -x plasmashell)" \
    "$(inlab pgrep -c -x kwin_wayland)" \
    "$(inlab sh -c 'grep -c "^plugin=" /home/classroom/.config/plasma-org.kde.plasma.desktop-appletsrc')" \
    "$(insession systemctl --user is-active ekklesia-classroom-audio.service)"
