#!/usr/bin/env python3.12

import json
import shutil
import subprocess as sp

from pathlib import Path


def main() -> int:
    if not Path("./flake.nix").exists():
        raise Exception(
            "You need to be in the root of the project (where the `flake.nix` is)"
        )
    response = sp.run(
        [shutil.which("nix"), "flake", "show", "--json"], capture_output=True
    )

    json_data = json.loads(response.stdout.decode("utf-8"))
    packages = json_data.get("packages")

    built_packages_paths = []
    for package in packages.get("x86_64-linux").keys():
        try:
            out_path = (
                sp.check_output(
                    [
                        shutil.which("nix"),
                        "build",
                        f".#{package}",
                        "--no-link",
                        "--print-out-paths",
                    ],
                )
                .decode("utf-8")
                .strip()
            )
            built_packages_paths.append(out_path)
            print("\n".join(built_packages_paths))
        except sp.CalledProcessError as err:
            print(f"Failed building package {package}")            
    return 0


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