#!/bin/bash
set -e

sway_pid=""
pipewire_pid=""
wireplumber_pid=""
portal_pid=""
wlr_portal_pid=""

# reexec this script inside a dbus session if we're not in one
if [[ -z "$DBUS_SESSION_BUS_ADDRESS" ]]; then
    export XDG_RUNTIME_DIR="$AUTOPKGTEST_TMP/run"
    export HOME="$AUTOPKGTEST_TMP/home"
    export XDG_CONFIG_HOME="$HOME/.config"
    export WAYLAND_DISPLAY=wayland-1
    export XDG_BACKEND=wayland
    export XDG_SESSION_TYPE=wayland
    export XDG_CURRENT_DESKTOP=sway

    mkdir -m 0700 -p "$XDG_RUNTIME_DIR" "$HOME" "$XDG_CONFIG_HOME"
    cd "$AUTOPKGTEST_TMP"

    exec dbus-run-session -- "$0" "$@"
fi

export WLR_BACKENDS=headless
export WLR_LIBINPUT_NO_DEVICES=1

echo "Starting sway"
sway --config /dev/null &
sway_pid=$!

kill_if_defined() {
    pid=$1

    [[ -z "$pid" ]] || kill "$pid" || true
}

cleanup() {
    kill_if_defined "$sway_pid"
    kill_if_defined "$pipewire_pid"
    kill_if_defined "$wireplumber_pid"
    kill_if_defined "$portal_pid"
    kill_if_defined "$wlr_portal_pid"
}

trap cleanup INT TERM EXIT

# export QT_DEBUG_PLUGINS=1
# export WAYLAND_DEBUG=1

wait_for_socket() {
    socket=$1
    echo "Waiting for socket $socket"

    deadline=$(( "$(date +%s)" + 300 ))
    while [[ "$(date +%s)" -lt "$deadline" ]]; do
        ! [[ -S "$socket" ]] || break
        sleep 1
    done

    echo "$socket is alive"
}

echo "Starting pipewire"
pipewire &
pipewire_pid=$!

echo "Starting wireplumber"
wireplumber &
wireplumber_pid=$!

wait_for_socket "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY"
wait_for_socket "$XDG_RUNTIME_DIR/pipewire-0"
wait_for_socket "$XDG_RUNTIME_DIR/pipewire-0-manager"

echo "Configuring xdg-desktop-portal-wlr"
mkdir -m 0700 -p "$XDG_CONFIG_HOME/xdg-desktop-portal-wlr"
cat << 'EOF' > "$XDG_CONFIG_HOME/xdg-desktop-portal-wlr/config"
[screencast]
chooser_type = none
output_name = HEADLESS-1
EOF

echo "Starting desktop portal"
/usr/libexec/xdg-desktop-portal &
portal_pid=$!

echo "Starting wlr desktop portal"
/usr/libexec/xdg-desktop-portal-wlr &
wlr_portal_pid=$!

# wait for portals
echo "Waiting for portals"
gdbus wait --session --timeout 120 org.freedesktop.portal.Desktop
gdbus wait --session --timeout 120 org.freedesktop.impl.portal.desktop.wlr

echo "Running flameshot"
outfile="screenshot.png"
flameshot screen -n 0 -p "$outfile"

echo "Verifying that flameshot has saved a screenshot"
file "$outfile" | grep "PNG image data"
