#!/usr/bin/env python3
"""Sandbox escape hatch for execute_code elevated steps.

Connects to the socket at OLLIE_ELEVATE_SOCKET, sends the command and cwd,
and returns the result. The adapter listening on that socket is responsible
for running the command outside the Landlock sandbox.

Usage: elevate -- <cmd>
"""
import sys
sys.path = sys.path[1:]  # strip script dir — may be a non-navigable fs (e.g. 9P)
import json
import os
import socket


def default_socket_path():
    xdg = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
    return os.path.join(xdg, "ollie", "elevate.sock")


def main():
    sock_path = os.environ.get("OLLIE_ELEVATE_SOCKET") or default_socket_path()

    if len(sys.argv) < 3:
        print("usage: elevate -- <cmd>", file=sys.stderr)
        sys.exit(1)

    req = json.dumps({"cmd": sys.argv[2], "cwd": os.getcwd()}).encode() + b"\n"

    sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        sock.connect(sock_path)
    except OSError as e:
        print(f"elevate: connect {sock_path}: {e}", file=sys.stderr)
        sys.exit(1)

    with sock:
        sock.sendall(req)
        sock.shutdown(socket.SHUT_WR)
        data = b""
        while chunk := sock.recv(65536):
            data += chunk

    resp = json.loads(data)
    if resp.get("stdout"):
        sys.stdout.write(resp["stdout"])
    if resp.get("stderr"):
        sys.stderr.write(resp["stderr"])
    sys.exit(resp.get("exit_code", 0))


if __name__ == "__main__":
    main()
