"""Mirror a line stream to stdout and a log that may be atomically replaced."""
import sys
import os
from pathlib import Path
import shutil
import tempfile


def mirror(source,output,path):
    path=Path(path)
    # Keep an independent spool: an external snapshot can replace the live
    # path with an older copy between writes. Reopening alone cannot recover
    # already-lost lines. TemporaryFile lives outside the watched output tree.
    with tempfile.TemporaryFile(mode='w+b') as spool:
        if path.exists():
            with path.open('rb') as previous:shutil.copyfileobj(previous,spool)
        for line in source:
            spool.write(line)
            with path.open('ab') as log:log.write(line)
            output.write(line);output.flush()
        spool.flush();spool.seek(0)
        staged=None
        try:
            with tempfile.NamedTemporaryFile(mode='wb',dir=path.parent,prefix='.suite35_log_',delete=False) as final:
                staged=Path(final.name)
                shutil.copyfileobj(spool,final)
                final.flush();os.fsync(final.fileno())
            staged.replace(path)
        finally:
            if staged is not None and staged.exists():staged.unlink()


if __name__=='__main__':
    mirror(sys.stdin.buffer,sys.stdout.buffer,sys.argv[1])
