#!/usr/bin/python3
"""Capture installer milestones on the actual boot USB. Preserve user privacy."""
from pathlib import Path
import subprocess
import sys
import time

sys.path.insert(0, "/usr/local/lib/newworld-installer")
from progress import Journal, Progress

LOGGER = "/usr/lib/newworld-installer/usb-log"

def log(*args):
    return subprocess.run([LOGGER, *args], check=False).returncode

def main():
    flags = Path("/proc/cmdline").read_text().split()
    if "newworld.debug=1" in flags:
        # The form and privileged installer deny installation on this boot.
        # The status file remains available even when a USB cannot be written.
        log("diagnose")
        return
    if "newworld.autoinstall=1" not in flags:
        return
    log("start")
    log("snapshot")
    log("event", "waiting", "0")
    journal = Journal()
    model = Progress(time.monotonic())
    last = None
    identity = None
    while True:
        records = journal.read()
        if identity != journal.identity:
            identity = journal.identity
            model = Progress(time.monotonic())
            last = None
        for record in records:
            model.accept(record, time.monotonic())
            update = model.stage, int(model.percent)
            if update != last:
                log("event", update[0], str(update[1]))
                last = update
            # The privileged worker flushes the terminal result synchronously.
            # Stay available for the next authorized attempt on the same boot.
            if model.status != "running":
                break
        time.sleep(0.8)

if __name__ == "__main__":
    main()
