#!/bin/sh
# i3 and i3bar read the DPI (Xft.dpi in the X resources) once, when they
# start. gsd-xsettings publishes it at the display scale GNOME Flashback sets
# up, so regolith-x11.service has to start i3 after gsd-xsettings, which
# itself comes after gnome-session-initialized.target (regolith-desktop#900).
#
# Logs a user in to the Regolith X11 session through PAM and logind, as a
# display manager does, on Xorg's dummy driver with two 2560x1440 outputs,
# at 100 % and at 200 % (org.gnome.desktop.interface scaling-factor). At
# 200 %, checks that Xft.dpi is 192 and that i3's bar on each output and its
# title bars are as large as after restarting i3 by hand, and differ from
# 100 %. Also checks that systemd found no ordering cycle, that the session
# reaches gnome-session.target and graphical-session.target, that i3 comes
# back at the same size after it crashes, and that logging out ends the
# session.
set -eu

if [ ! -d /run/systemd/system ] ||
   ! busctl --system status org.freedesktop.login1 >/dev/null 2>&1; then
    echo "SKIP: needs systemd as init and systemd-logind"
    exit 77
fi

user=regolith-autopkgtest
login_unit=regolith-autopkgtest-login
display=:73
tmp=${AUTOPKGTEST_TMP:-$(mktemp -d)}
created=no
if ! id "$user" >/dev/null 2>&1; then
    useradd --create-home --shell /bin/sh "$user"
    created=yes
fi
uid=$(id -u "$user")
home=$(getent passwd "$user" | cut -d: -f6)
rt=/run/user/$uid
fail=0
xorg=""

cleanup() {
    systemctl stop "$login_unit" >/dev/null 2>&1 || true
    systemctl reset-failed "$login_unit" >/dev/null 2>&1 || true
    loginctl terminate-user "$user" >/dev/null 2>&1 || true
    [ -z "$xorg" ] || kill "$xorg" 2>/dev/null || true
    if [ "$created" = yes ]; then
        for _ in 1 2 3 4 5 6 7 8 9 10; do
            pgrep -u "$uid" >/dev/null 2>&1 || break
            sleep 1
        done
        userdel --remove "$user" >/dev/null 2>&1 || true
    fi
}
trap cleanup EXIT

as_user() {
    runuser -u "$user" -- env XDG_RUNTIME_DIR="$rt" DISPLAY="$display" \
        DBUS_SESSION_BUS_ADDRESS="unix:path=$rt/bus" "$@"
}
uctl() { as_user systemctl --user "$@"; }
i3_pid() { pgrep -u "$uid" -x i3 || true; }
wait_for() { # wait_for <seconds> <command...>
    n=$(($1 * 5))
    shift
    while [ "$n" -gt 0 ]; do
        "$@" && return 0
        sleep 0.2
        n=$((n - 1))
    done
    return 1
}

# Xorg with the dummy driver and two outputs
cat > "$tmp/xorg.conf" <<'EOF'
Section "ServerFlags"
    Option "AutoAddDevices" "false"
EndSection
Section "Device"
    Identifier "dummy"
    Driver "dummy"
    VideoRam 256000
EndSection
Section "Monitor"
    Identifier "Monitor0"
    HorizSync 5.0-1000.0
    VertRefresh 5.0-200.0
EndSection
Section "Screen"
    Identifier "Screen0"
    Device "dummy"
    Monitor "Monitor0"
    DefaultDepth 24
    SubSection "Display"
        Depth 24
        Modes "1024x768"
        Virtual 5120 1440
    EndSubSection
EndSection
EOF
Xorg "$display" -config "$tmp/xorg.conf" -ac -noreset -nolisten tcp \
    -logfile "$tmp/xorg.log" >"$tmp/xorg.out" 2>&1 &
xorg=$!
if ! wait_for 20 xdpyinfo -display "$display" >/dev/null 2>&1; then
    tail -n 20 "$tmp/xorg.log" || true
    echo "SKIP: Xorg with the dummy driver does not start here"
    exit 77
fi
export DISPLAY=$display
xrandr --newmode 2560x1440 312.25 2560 2752 3024 3488 1440 1443 1448 1493 -hsync +vsync
for o in DUMMY0 DUMMY1; do xrandr --addmode $o 2560x1440; done
xrandr --output DUMMY0 --mode 2560x1440 --pos 0x0 --primary \
       --output DUMMY1 --mode 2560x1440 --pos 2560x0
xrandr --listactivemonitors

# The height of each bar and the title bar of the test window
looks() {
    bars=$(xwininfo -root -tree \
        | sed -n 's/.*"i3bar for output \([^"]*\)".* [0-9]*x\([0-9]*\)[-+][0-9]*[-+][0-9]* .*/\1=\2/p' \
        | sort | tr '\n' ' ')
    title=$(as_user i3-msg -t get_tree 2>/dev/null | python3 -c '
import json, sys
def walk(n):
    if n.get("window_properties", {}).get("class") == "Xmessage":
        return n["deco_rect"]["height"]
    for c in n.get("nodes", []) + n.get("floating_nodes", []):
        h = walk(c)
        if h is not None:
            return h
print(walk(json.load(sys.stdin)))' 2>/dev/null || true)
    echo "bars: ${bars}title bar: $title"
}
two_bars_and_title() {
    looks | grep -q '^bars: DUMMY0=[0-9]* DUMMY1=[0-9]* title bar: [0-9]'
}
session_up() {
    [ "$(uctl is-active regolith-x11.service 2>/dev/null)" = active ] &&
        [ "$(uctl is-active graphical-session.target 2>/dev/null)" = active ]
}
session_gone() {
    ! systemctl -q is-active "$login_unit" && [ -z "$(i3_pid)" ]
}
open_window() {
    as_user xmessage -geometry +100+100 regolith-autopkgtest >/dev/null 2>&1 &
    # Regolith draws pixel borders; give the test window a title bar
    wait_for 15 sh -c "DISPLAY=$display xwininfo -root -tree | grep -q '\"xmessage\"'" || true
    sleep 0.5
    as_user i3-msg -q '[class="Xmessage"] border normal' || true
}

# login <scale>: log in, wait for i3 with both bars and the test window
login() {
    systemctl stop "$login_unit" >/dev/null 2>&1 || true
    systemctl reset-failed "$login_unit" >/dev/null 2>&1 || true
    xrdb -remove
    runuser -u "$user" -- env -u XDG_RUNTIME_DIR dbus-run-session -- \
        gsettings set org.gnome.desktop.interface scaling-factor "$1"
    since=$(date '+%Y-%m-%d %H:%M:%S')
    # A user manager that starts with the login may not be on its bus yet
    # when gnome-session asks it to start the session; start it first.
    systemctl start "user@$uid.service"
    if ! wait_for 30 as_user busctl --user status org.freedesktop.systemd1 >/dev/null 2>&1; then
        echo "FAIL: the user manager is not on the user bus"
        exit 1
    fi
    systemd-run --quiet --unit="$login_unit" \
        -p PAMName=login -p User="$user" -p WorkingDirectory="$home" \
        -E DISPLAY="$display" -E XDG_SESSION_TYPE=x11 -E XDG_SESSION_CLASS=user \
        -E XDG_SESSION_DESKTOP=regolith-x11 -E LANG=C.UTF-8 \
        /usr/bin/regolith-session-x11-launch
    if ! wait_for 90 session_up; then
        echo "FAIL: the X11 session did not start"
        journalctl --no-pager -q --since "$since" -u "$login_unit" | tail -n 20
        journalctl --no-pager -q --since "$since" _UID="$uid" \
            | grep -E 'regolith|gnome-session|i3|XSettings|cycle' | tail -n 40
        exit 1
    fi
    open_window
    if ! wait_for 20 two_bars_and_title; then
        echo "FAIL: no bar on each output or no test window: $(looks)"
        exit 1
    fi
    sleep 1
}
logout() {
    as_user gnome-session-quit --logout --no-prompt || true
    if wait_for 30 session_gone; then
        echo "ok: logging out ends the session"
    else
        echo "FAIL: the session is still running 30 s after logging out"
        fail=1
    fi
}
check() { # check <what> <command...>
    what=$1
    shift
    if "$@"; then echo "ok: $what"; else echo "FAIL: $what"; fail=1; fi
}

echo "=== login at 100 %"
login 1
at100=$(looks)
echo "at 100 %: $at100"
logout

echo "=== login at 200 %"
login 2
at200=$(looks)
dpi=$(xrdb -query | sed -n 's/^Xft\.dpi:\t//p')
echo "at 200 %: $at200, Xft.dpi $dpi"
journalctl --no-pager -q --since "$since" _UID="$uid" -o cat > "$tmp/journal"
check "Xft.dpi is 192" [ "$dpi" = 192 ]
check "the bars and title bars at 200 % differ from 100 %" [ "$at200" != "$at100" ]
if grep -i 'ordering cycle' "$tmp/journal"; then
    echo "FAIL: systemd found an ordering cycle at login"
    fail=1
else
    echo "ok: no ordering cycle at login"
fi
for unit in org.gnome.SettingsDaemon.XSettings.service gnome-flashback.service \
            gnome-session.target graphical-session.target; do
    check "$unit is active" [ "$(uctl is-active "$unit" 2>/dev/null)" = active ]
done

as_user i3-msg -q restart
sleep 4
as_user i3-msg -q '[class="Xmessage"] border normal' || true
sleep 0.5
restarted=$(looks)
echo "after restarting i3 by hand: $restarted"
check "i3 started at the published DPI: restarting it changes nothing" [ "$restarted" = "$at200" ]

old=$(i3_pid)
kill -KILL "$old"
wait_for 20 sh -c "pgrep -u $uid -x i3 | grep -vx '$old' >/dev/null" || true
open_window
wait_for 20 two_bars_and_title || true
sleep 1
crashed=$(looks)
echo "after i3 crashed and the session started it again: $crashed"
check "i3 comes back after a crash at the same size" [ "$crashed" = "$at200" ]
logout

exit $fail
