#!/usr/bin/python3 -I
"""systemd-run for OpenRC hosts: the `--user` form, forwarded to systemd-run-agent.

The agent runs in the graphical session and takes the place of the systemd user manager: the
command runs with the agent's environment plus --setenv values, outside the caller's process
tree, so a caller's no_new_privs (Proton) does not apply to it.

Supported: --user, --wait, --pipe/-P, --setenv/-E, --same-dir/-d, --working-directory; accepted
and ignored: --collect/-G, --quiet/-q, --unit/-u, --description, --property/-p. Anything else
fails as systemd-run does on a host without a user manager.
"""
import json
import os
import socket
import sys

VALUE = {"-E", "--setenv", "-u", "--unit", "--description", "-p", "--property", "--working-directory"}
IGNORED = {"-G", "--collect", "-q", "--quiet", "-u", "--unit", "--description", "-p", "--property"}


def fail(msg):
    print(msg, file=sys.stderr)
    sys.exit(1)


args = sys.argv[1:]
user = wait = pipe = False
env, cwd, i = {}, None, 0
while i < len(args) and args[i].startswith("-"):
    arg = args[i]
    i += 1
    if arg == "--":
        break
    opt, eq, val = arg.partition("=")
    if opt in VALUE and not eq:
        if i == len(args):
            fail(f"Option '{opt}' requires an argument.")
        val, i = args[i], i + 1
    if opt == "--user":
        user = True
    elif opt == "--wait":
        wait = True
    elif opt in ("-P", "--pipe"):
        pipe = True
    elif opt in ("-E", "--setenv"):
        key, has, value = val.partition("=")
        env[key] = value if has else os.environ.get(key, "")
    elif opt in ("-d", "--same-dir"):
        cwd = os.getcwd()
    elif opt == "--working-directory":
        cwd = val
    elif opt not in IGNORED:
        fail(f"systemd-run (eac-openrc-compat): unsupported option '{arg}'.")
cmd = args[i:]
if not user:
    fail("System has not been booted with systemd as init system (PID 1). Can't operate.")
if not cmd:
    fail("Command line to execute required.")

runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}"
sock = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
try:
    sock.connect(os.path.join(runtime, "systemd-run-agent.sock"))
except OSError as e:
    fail(f"Failed to connect to user scope bus: systemd-run-agent is not running ({e.strerror}).")
request = json.dumps({"argv": cmd, "env": env, "cwd": cwd, "wait": wait}).encode()
socket.send_fds(sock, [request], [0, 1, 2] if pipe else [])
reply = sock.recv(65536)
sys.exit(json.loads(reply)["status"] if reply else 1)
