#!/usr/bin/python3
"""Show genuine USB-environment package progress before the names screen opens."""
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import time

from progress import clock_text

STATUS = re.compile(r"^pmstatus:[^:]*:(?:[A-Za-z][a-z0-9-]*:)?(\d+(?:\.\d+)?):")
HE = "locales=he_IL." in Path("/proc/cmdline").read_text()
PLYMOUTH = shutil.which("plymouth")

def display(percent, remaining, error=False):
    eta = ("מחשב…" if HE else "estimating…") if remaining is None else clock_text(remaining)
    if error:
        text = (f"הכנת סביבת ההתקנה נעצרה · ⁦{percent}%⁩" if HE else f"USB startup stopped | {percent}%")
    else:
        text = (f"הכנת סביבת ההתקנה בכונן USB · ⁦{percent}%⁩ · זמן משוער לסיום ⁦{eta}⁩" if HE else
                f"Preparing the installer USB environment | {percent}% | Estimated time left {eta}")
    print(text,flush=True)
    if PLYMOUTH:
        try:
            result = subprocess.run([PLYMOUTH, "display-message", "--text="+text],
                                    stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,timeout=1)
            if result.returncode==0:return
        except (OSError,subprocess.TimeoutExpired):
            pass
    try:
        fd=os.open("/dev/console", os.O_WRONLY | os.O_NOCTTY | os.O_NONBLOCK)
        try:os.write(fd, (text+"\n").encode())
        finally:os.close(fd)
    except OSError:
        pass

def main():
    start=time.monotonic()
    last_percent=0
    last_display=start
    display(0,None)
    env={**os.environ,"LC_NUMERIC":"C","APT_CONFIG":"/usr/local/lib/newworld-installer/apt-progress.conf"}
    with subprocess.Popen(["/usr/local/lib/compact-build/install-offline","live"],
                          env=env,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,
                          text=True,errors="replace") as worker:
        for line in worker.stdout:
            match=STATUS.match(line)
            if not match:
                sys.stdout.write(line)
                continue
            percent=max(last_percent,min(97,int(float(match.group(1))*.97)))
            now=time.monotonic()
            if percent>last_percent and (now-last_display>=1 or percent-last_percent>=3):
                last_percent=percent
                last_display=now
                remaining=max(1,round((now-start)*(100-percent)/percent))
                display(percent,remaining)
        code=worker.wait()
    display(last_percent if code else 100,None if code else 0,error=bool(code))
    return code

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