#!/usr/bin/env python3
"""Check whether the captured session's Wayland socket accepts connections."""
import os
from pathlib import Path
import socket


def session_ready(environment=None):
    environment = os.environ if environment is None else environment
    display = environment.get("WAYLAND_DISPLAY")
    if not display:
        return False
    path = Path(display)
    if not path.is_absolute():
        runtime = environment.get("XDG_RUNTIME_DIR")
        if not runtime:
            return False
        path = Path(runtime) / path
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
            connection.settimeout(1)
            connection.connect(str(path))
    except OSError:
        return False
    return True


if __name__ == "__main__":
    raise SystemExit(0 if session_ready() else 1)
