#!/usr/bin/env python3
"""Build a committed Flatpak manifest locally before publishing its GitHub release."""
import argparse
import hashlib
import json
from pathlib import Path, PurePosixPath
import subprocess
import tempfile
from urllib.parse import unquote, urlsplit


def sources(modules):
    for module in modules:
        if not isinstance(module, dict):
            raise ValueError("Declare modules directly in the JSON manifest.")
        yield from module.get("sources", [])
        yield from sources(module.get("modules", []))


def validate(args):
    checkout = args.checkout.resolve()
    manifest_path = PurePosixPath(args.manifest)
    if not manifest_path.parts or manifest_path.is_absolute() or ".." in manifest_path.parts:
        raise ValueError("Use a manifest path relative to the checkout.")
    git = ["git", "-C", str(checkout)]
    commit = subprocess.check_output([*git, "rev-parse", "HEAD"], text=True).strip()
    manifest = json.loads(subprocess.check_output([*git, "show", f"{commit}:{manifest_path}"]))
    if not isinstance(manifest, dict) or not isinstance(manifest.get("modules"), list):
        raise ValueError("Use a JSON Flatpak manifest with a list of modules.")
    manifest.setdefault("branch", "stable")

    assets = {}
    for path in args.asset:
        if path.name in assets:
            raise ValueError(f"More than one local asset is named {path.name}.")
        assets[path.name] = path.resolve(strict=True)
    matched_assets = set()
    main_source = False
    for source in sources(manifest["modules"]):
        if not isinstance(source, dict):
            raise ValueError("Declare each source directly in the JSON manifest.")
        if source.get("type") == "git" and source.get("commit") == "@ENZIM_SOURCE_COMMIT@":
            if source.get("disable-submodules") is not True:
                raise ValueError("Set disable-submodules to true on the app's Git source.")
            source.update(url=checkout.as_uri(), commit=commit)
            main_source = True
        if source.get("type") in ("archive", "file"):
            url = source.get("url")
            if not isinstance(url, str):
                raise ValueError("Give each archive or file source a URL.")
            name = unquote(PurePosixPath(urlsplit(url).path).name)
            if name in assets:
                path = assets[name]
                with path.open("rb") as stream:
                    checksum = hashlib.file_digest(stream, "sha256").hexdigest()
                if checksum != source.get("sha256"):
                    raise ValueError(f"{name} has SHA-256 {checksum}. Update the manifest or use the matching file.")
                source["url"] = path.as_uri()
                matched_assets.add(name)
    if not main_source:
        raise ValueError("Declare the checkout's Git source with @ENZIM_SOURCE_COMMIT@.")
    if matched_assets != assets.keys():
        unmatched = sorted(assets.keys() - matched_assets)
        raise ValueError("These local assets have no matching URL filename in the manifest: " + ", ".join(unmatched))

    work = Path(tempfile.mkdtemp(prefix="enzim-flatpak-check."))
    recipe = work / "manifest.json"
    recipe.write_text(json.dumps(manifest, indent=2) + "\n")
    print(f"Testing commit {commit} in {work}", flush=True)
    build = work / "build"
    builder = ["flatpak-builder", "--user", "--sandbox", "--disable-rofiles-fuse",
               f"--jobs={args.jobs}", f"--state-dir={work / 'state'}"]
    subprocess.run([*builder, "--download-only", build, recipe], check=True)
    subprocess.run([*builder, "--build-only", "--disable-download", build, recipe], check=True)
    subprocess.run([*builder, "--finish-only", "--disable-download", build, recipe], check=True)
    print(f"Flatpak built and finished successfully in {build}")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--checkout", type=Path, default=Path("."), help="Git checkout to read at HEAD")
    parser.add_argument("--manifest", required=True, help="committed JSON manifest path relative to the checkout")
    parser.add_argument("--asset", type=Path, action="append", default=[],
                        help="local asset with the same filename and SHA-256 as its manifest URL (repeatable)")
    parser.add_argument("--jobs", type=int, default=8, choices=range(1, 13))
    args = parser.parse_args()
    try:
        validate(args)
    except (OSError, ValueError, KeyError, subprocess.CalledProcessError) as error:
        parser.exit(1, f"Local Flatpak check failed. {error}\n")


if __name__ == "__main__":
    main()
