#!/usr/bin/python3 -I
"""Socket activation without systemd, like a .socket unit with Accept=no.

Usage: socket-activate [-n] {stream|seqpacket} ADDRESS COMMAND [ARGS...]
ADDRESS is @NAME for an abstract Unix socket, else a filesystem path. When a client connects,
COMMAND starts with the listening socket as fd 3, LISTEN_FDS=1 and LISTEN_PID; after it exits
the next connection starts it again. -n sets O_NONBLOCK on the socket (NonBlocking=yes).
SIGTERM is passed on to a running COMMAND.
"""
import os
import select
import signal
import socket
import sys
import time

args = sys.argv[1:]
nonblocking = args[:1] == ["-n"]
if nonblocking:
    args = args[1:]
kind, address, cmd = args[0], args[1], args[2:]
sock = socket.socket(socket.AF_UNIX, {"stream": socket.SOCK_STREAM, "seqpacket": socket.SOCK_SEQPACKET}[kind])
if address.startswith("@"):
    sock.bind("\0" + address[1:])
else:
    if os.path.exists(address):
        os.unlink(address)
    sock.bind(address)
sock.listen(128)
sock.setblocking(not nonblocking)
child = 0


def stop(signum, _):
    if child:
        os.kill(child, signal.SIGTERM)
        os.waitpid(child, 0)
    sys.exit(0)


signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
print(f"listening on {address}", file=sys.stderr, flush=True)
while True:
    select.select([sock], [], [])
    child = os.fork()
    if child == 0:
        os.dup2(sock.fileno(), 3)
        os.set_inheritable(3, True)
        os.environ.update(LISTEN_FDS="1", LISTEN_PID=str(os.getpid()))
        os.environ.pop("LISTEN_FDNAMES", None)
        try:
            os.execvp(cmd[0], cmd)
        finally:
            os._exit(127)
    started = time.monotonic()
    print(f"started {cmd[0]} as pid {child}", file=sys.stderr, flush=True)
    _, status = os.waitpid(child, 0)
    child = 0
    print(f"{cmd[0]} exited with {os.waitstatus_to_exitcode(status)}", file=sys.stderr, flush=True)
    # ponytail: fixed 1 s pause after a quick exit instead of systemd's StartLimitBurst accounting
    if time.monotonic() - started < 1:
        time.sleep(1)
