#!/usr/bin/env python3
"""daemonize.py — run a command so it OUTLIVES the shell that launched it.

TWO THINGS THIS LANE LEARNED THE HARD WAY.

`nohup … &` is not enough. A 1080p encode started that way was killed mid-write when
the harness tore down its shell, and produced an unplayable file — `moov atom not
found`, because the moov atom is written last. A long ffmpeg or a long render driver
must be genuinely detached, not merely backgrounded.

`setsid` DOES NOT EXIST ON macOS. The "double-fork + setsid" recipe everyone quotes is
Linux; on macOS the binary is simply absent and the shell reports "command not found"
in a log nobody reads. Python has os.setsid() built in, so the fork is done here:

    fork #1  -> the parent returns to the shell immediately
    setsid   -> the child leaves the shell's session and process group, so a
                group-wide signal aimed at the shell cannot reach it
    fork #2  -> guarantees the daemon is not a session leader and can never acquire
                a controlling terminal
    stdio    -> redirected to the log. A daemon holding the shell's pipes open keeps
                that shell alive and defeats the whole point.

It prints the daemon's real pid, read back from the pidfile the child wrote, so the
caller can PROVE it is running rather than assume it. Three driver runs were reported
as "launched" when they had already died.

Usage:
  daemonize.py --log <file> --pid <file> [--cwd <dir>] -- <command> [args...]
"""
from __future__ import annotations

import argparse
import os
import sys
import time


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--log", required=True)
    ap.add_argument("--pid", required=True)
    ap.add_argument("--cwd", default=None)
    ap.add_argument("command", nargs=argparse.REMAINDER)
    args = ap.parse_args()

    command = [a for a in args.command if a != "--"]
    if not command:
        print("daemonize: no command given (use -- before it)", file=sys.stderr)
        raise SystemExit(2)

    log, pidfile = os.path.abspath(args.log), os.path.abspath(args.pid)
    os.makedirs(os.path.dirname(log), exist_ok=True)
    os.makedirs(os.path.dirname(pidfile), exist_ok=True)
    # Remove a stale pidfile first, or the parent below reports the PREVIOUS run's pid
    # and everything downstream watches a process that is already gone.
    try:
        os.unlink(pidfile)
    except FileNotFoundError:
        pass

    if os.fork() > 0:
        for _ in range(100):
            try:
                pid = open(pidfile, encoding="utf-8").read().strip()
            except FileNotFoundError:
                pid = ""
            if pid:
                print(pid)
                return
            time.sleep(0.1)
        print("daemonize: the child never wrote a pidfile", file=sys.stderr)
        raise SystemExit(1)

    os.setsid()
    if os.fork() > 0:
        os._exit(0)

    if args.cwd:
        os.chdir(args.cwd)
    handle = os.open(log, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o644)
    devnull = os.open(os.devnull, os.O_RDONLY)
    os.dup2(devnull, 0)
    os.dup2(handle, 1)
    os.dup2(handle, 2)
    with open(pidfile, "w", encoding="utf-8") as fh:
        fh.write(str(os.getpid()))
    os.execvp(command[0], command)


if __name__ == "__main__":
    main()
