#!/usr/bin/python3
"""Root helper for VolnOS Setup — does the privileged first-boot install.

Invoked by the GUI through pkexec (a polkit rule lets the gnome-initial-setup user
run it without a password — there is no human account yet). Reads the choices
manifest as JSON on stdin and streams progress on stdout:

    PROGRESS <0..1> <message>
    DONE                       (success)
    ERROR <message>            (failure)

All the real work lives in volnos_preinstall.provision so it is shared with the
reconciler and stays testable.
"""
import json
import sys
import traceback

sys.path.insert(0, "/usr/lib/volnos-preinstall")

from volnos_preinstall import provision  # noqa: E402


def main() -> int:
    raw = sys.stdin.read()
    try:
        manifest = json.loads(raw) if raw.strip() else {}
    except ValueError as exc:
        provision.error(f"invalid manifest: {exc}")
        return 2
    try:
        ok, message = provision.apply(manifest)
    except Exception as exc:  # noqa: BLE001 - report any failure to the GUI
        provision._log("unexpected failure traceback:\n" + traceback.format_exc())
        provision.error(f"{exc} (details in {provision.LOG_PATH})")
        return 1
    if ok:
        provision.done()
        return 0
    provision.error(message or "some items could not be installed")
    return 1


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