"""Create lazy definitions to reference the pre-built protoc toolchains.

Ensures that Bazel only downloads required binaries for selected toolchains.
In particular, see comment below on the toolchain#toolchain attribute.
"""

load("//toolchain:platforms.bzl", "PROTOBUF_PLATFORMS")
load(":protoc_authenticity.bzl", "protoc_authenticity")
load(":tool_integrity.bzl", "RELEASE_VERSION")

[
    toolchain(
        name = "{}_toolchain".format(platform.replace("-", "_")),
        exec_compatible_with = meta["compatible_with"],
        # Toolchain resolution will only permit this toolchain if the config_setting for prefer_prebuilt_protoc is true,
        target_settings = ["@com_google_protobuf//bazel/flags:prefer_prebuilt_protoc.flag_set"],
        # Bazel does not follow this attribute during analysis, so the referenced repo
        # will only be fetched if this toolchain is selected.
        toolchain = "@prebuilt_protoc.{}//:prebuilt_protoc_toolchain".format(platform.replace("-", "_")),
        toolchain_type = "@com_google_protobuf//bazel/private:proto_toolchain_type",
    )
    for platform, meta in PROTOBUF_PLATFORMS.items()
    if not RELEASE_VERSION.endswith("-dev")
]

# Support verification of user-registered toolchains
protoc_authenticity(
    name = "authenticity_validation",
    fail_on_mismatch = select({
        "//bazel/flags:allow_nonstandard_protoc.flag_set": False,
        "//conditions:default": True,
    }),
    visibility = ["//visibility:public"],
)
