#!/usr/bin/env bash
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
WRAPPER="$ROOT/scripts/ci-with-test-display.sh"

bad() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }
ok() { printf 'OK: %s\n' "$*"; }

[[ -x "$WRAPPER" ]] || chmod +x "$WRAPPER"
bash -n "$WRAPPER" || bad 'bash -n ci-with-test-display.sh'

command -v Xvfb >/dev/null 2>&1 || {
  printf 'SKIP: Xvfb not installed\n'
  exit 0
}

if ! out="$("$WRAPPER" sh -c 'printf %s "$DISPLAY"')" 2>/dev/null; then
  printf 'SKIP: Xvfb could not start a private display in this environment\n'
  exit 0
fi
[[ "$out" =~ ^:9[0-9]$ ]] || bad "expected :90-:99 display, got: $out"
ok "allocates private display ($out)"

out="$("$WRAPPER" sh -c 'test -n "${WAYLAND_DISPLAY+x}" && printf set || printf unset')"
[[ "$out" == unset ]] || bad "WAYLAND_DISPLAY should be unset, got: $out"
ok 'unsets WAYLAND_DISPLAY'

out="$("$WRAPPER" sh -c 'printf %s "$GDK_BACKEND"')"
[[ "$out" == x11 ]] || bad "GDK_BACKEND should be x11, got: $out"
ok 'forces GDK_BACKEND=x11'

ok 'ci-with-test-display tests passed'
