#!/usr/bin/env python3

import os.path
import sys


def main(argv: list[str]) -> int:
    """
    Daemonizes the process and runs the specified command.
    The PID of the child process is written to the specified pidfile.
    """
    if not os.path.exists("/dev/null"):
        sys.stderr.write("This platform does not support daemonization.\n")
        return 1

    if not os.access("/dev/null", os.W_OK):
        sys.stderr.write("Cannot write to /dev/null\n")
        return 1

    if len(argv) < 3 or argv[1] in ("--help", "-h") or sys.argv[2] != "--":
        sys.stderr.write("Usage: daemonizer pidfile -- [command] [args...]")
        return 1

    pidfile = sys.argv[1]
    if pidfile == "-":
        pidfile = "/dev/stdout"
    elif not os.path.isabs(pidfile):
        pidfile = os.path.abspath(pidfile)

    from xpra.util.io import livefds
    from xpra.util.daemon import daemonize
    daemonize()

    from subprocess import Popen
    command = sys.argv[3:]
    try:
        proc = Popen(command, close_fds=True)
        pid = proc.pid

        with open(pidfile, "wb") as f:
            f.write(f"{pid}\n".encode("latin1"))
            f.flush()
            os.fsync(f.fileno())

        fds = livefds()
        for fd in fds:
            try:
                os.close(fd)
            except Exception:
                pass
        return proc.wait()
    except Exception:
        return 1
    finally:
        try:
            os.unlink(pidfile)
        except Exception:
            pass


if __name__ == "__main__":
    sys.exit(main(sys.argv))
