#!/usr/bin/python3
# SPDX-License-Identifier: GPL-2.0-or-later
"""Build a private GNSS runtime archive from a mounted Lenovo system image."""

from argparse import ArgumentParser
import hashlib
from pathlib import Path
import tarfile
import sys

from yogabook_gnss_runtime import (
    EXPECTED_GPSD_SHA256,
    RuntimeError,
    sha256_file,
    source_paths,
    validate_source_identity,
)


def main() -> int:
    parser = ArgumentParser()
    parser.add_argument("stock_system_root", type=Path)
    parser.add_argument("output", type=Path)
    args = parser.parse_args()

    try:
        root = args.stock_system_root.resolve(strict=True)
        validate_source_identity(root)
        gpsd = root / "vendor/bin/gpsd"
        actual = sha256_file(gpsd)
        if actual != EXPECTED_GPSD_SHA256:
            raise RuntimeError(
                f"unsupported stock gpsd: expected {EXPECTED_GPSD_SHA256}, got {actual}"
            )

        output = args.output.resolve()
        output.parent.mkdir(parents=True, exist_ok=True)
        with tarfile.open(output, "w") as archive:
            for runtime_name, source in source_paths(root):
                info = archive.gettarinfo(str(source), arcname=runtime_name)
                info.uid = info.gid = 0
                info.uname = info.gname = "root"
                info.mtime = 0
                with source.open("rb") as content:
                    archive.addfile(info, content)
    except (OSError, RuntimeError, tarfile.TarError) as error:
        print(f"ERROR: {error}", file=sys.stderr)
        return 1

    print(f"Created private runtime: {output}")
    print(f"SHA256: {sha256_file(output)}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
