#!/usr/bin/env python3
# Minimal greetd IPC mock — just enough for tanin-greet to render and dry-run a
# login WITHOUT real auth. greetd framing: native-endian u32 length + JSON.
# Usage:  python3 mockgreetd.py /tmp/mock-greetd.sock
import json, os, socket, struct, sys

SOCK = sys.argv[1] if len(sys.argv) > 1 else "/tmp/mock-greetd.sock"
try:
    os.unlink(SOCK)
except FileNotFoundError:
    pass

srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
srv.bind(SOCK)
srv.listen(8)
print(f"mock greetd listening on {SOCK}", flush=True)


def recv(conn):
    hdr = conn.recv(4)
    if len(hdr) < 4:
        return None
    n = struct.unpack("=I", hdr)[0]
    buf = b""
    while len(buf) < n:
        chunk = conn.recv(n - len(buf))
        if not chunk:
            break
        buf += chunk
    return json.loads(buf)


def send(conn, obj):
    data = json.dumps(obj).encode()
    conn.sendall(struct.pack("=I", len(data)) + data)


while True:
    conn, _ = srv.accept()
    try:
        while True:
            req = recv(conn)
            if req is None:
                break
            if req.get("type") == "create_session":
                send(conn, {"type": "auth_message",
                            "auth_message_type": "secret",
                            "auth_message": "Password:"})
            else:  # post_auth_message_response / start_session / cancel_session
                send(conn, {"type": "success"})
    except Exception as e:  # noqa: BLE001
        print("conn error:", e, flush=True)
    finally:
        conn.close()
