#!/usr/bin/python3 -I
"""Runs commands for systemd-run (eac-openrc-compat) in the graphical session.

Start it once per session, from the compositor's autostart. Each request comes from the
systemd-run in /usr/bin over $XDG_RUNTIME_DIR/systemd-run-agent.sock; only the agent's own user
may connect. The command gets the agent's environment plus the request's --setenv values and, with
--pipe, the caller's stdin/stdout/stderr. Every run is logged to syslog.
"""
import json
import os
import socket
import struct
import subprocess
import syslog
import threading

runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
path = os.path.join(runtime, "systemd-run-agent.sock")
syslog.openlog("systemd-run-agent")


def exit_status(code):
    return code if code >= 0 else 128 - code


def serve(conn):
    with conn:
        uid = struct.unpack("3i", conn.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))[1]
        if uid != os.getuid():
            return
        data, fds, _, _ = socket.recv_fds(conn, 1 << 20, 3)
        if not data:
            return
        req = json.loads(data)
        stdio = fds if len(fds) == 3 else [subprocess.DEVNULL, None, None]
        try:
            proc = subprocess.Popen(req["argv"], stdin=stdio[0], stdout=stdio[1], stderr=stdio[2],
                                    env=dict(os.environ, **req["env"]), start_new_session=True,
                                    cwd=req["cwd"] or os.path.expanduser("~"))
        except OSError as e:
            syslog.syslog(f"{req['argv'][0]}: {e.strerror}")
            conn.send(json.dumps({"status": 127}).encode())
            return
        finally:
            for fd in fds:
                os.close(fd)
        syslog.syslog(f"pid {proc.pid}: {' '.join(req['argv'])}")
        if not req["wait"]:
            conn.send(json.dumps({"status": 0}).encode())
        status = exit_status(proc.wait())
        syslog.syslog(f"pid {proc.pid} exited with {status}")
        if req["wait"]:
            conn.send(json.dumps({"status": status}).encode())


probe = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
if probe.connect_ex(path) == 0:
    raise SystemExit("systemd-run-agent is already running")
if os.path.exists(path):
    os.unlink(path)
server = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
server.bind(path)
server.listen(16)
syslog.syslog(f"listening on {path}")
while True:
    conn, _ = server.accept()
    threading.Thread(target=serve, args=(conn,), daemon=True).start()
