load("//bazel:defs.bzl", "otp_header_parse", "picotool_binary_data_header")

package(default_visibility = ["//visibility:public"])

picotool_binary_data_header(
    name = "rp2350_rom",
    src = "bootrom.end.bin",
    out = "rp2350.rom.h",
)

# TODO: Make it possible to build the prebuilt from source.
picotool_binary_data_header(
    name = "xip_ram_perms_elf",
    src = "//xip_ram_perms:xip_ram_perms_prebuilt",
    out = "xip_ram_perms_elf.h",
)

cc_library(
    name = "xip_ram_perms",
    srcs = ["xip_ram_perms.cpp"],
    hdrs = [
        "xip_ram_perms.h",
        "xip_ram_perms_elf.h",
    ],
    deps = [
        "//bazel:data_locs",
        "//lib/whereami",
    ],
)

filegroup(
    name = "data_locs_header",
    srcs = ["data_locs.h"],
)

otp_header_parse(
    name = "otp_header",
    src = "@pico-sdk//src/rp2350/hardware_regs:otp_data_header",
    out = "rp2350.json.h",
)

cc_binary(
    name = "picotool",
    srcs = [
        "cli.h",
        "clipp/clipp.h",
        "main.cpp",
        "otp.cpp",
        "otp.h",
        "rp2350.json.h",
        "rp2350.rom.h",
        "xip_ram_perms.cpp",
    ],
    copts = select({
        "@rules_cc//cc/compiler:msvc-cl": [
            "/std:c++20",
        ],
        "//conditions:default": [
            "-fexceptions",
            "-Wno-delete-non-abstract-non-virtual-dtor",
            "-Wno-reorder-ctor",
            "-Wno-unused-variable",
            "-Wno-unused-but-set-variable",
        ],
    }),
    defines = [
        # TODO: There's probably a nicer way to share the version with CMake.
        'PICOTOOL_VERSION=\\"2.0.0\\"',
        'SYSTEM_VERSION=\\"host\\"',
        'COMPILER_INFO=\\"local\\"',
        "SUPPORT_A0=0",
        "SUPPORT_A2=1",
        "PICOTOOL_CODE_OTP=0",
        # TODO: Make it possible to compile from source.
        "USE_PRECOMPILED=1",
    ],
    # Windows does not behave nicely with the automagic force_dynamic_linkage_enabled.
    dynamic_deps = select({
        "@rules_libusb//:force_dynamic_linkage_enabled": ["@libusb//:libusb_dynamic"],
        "//conditions:default": [],
    }),
    deps = [
        ":xip_ram_perms",
        "//bazel:data_locs",
        "//bintool",
        "//elf",
        "//elf2uf2",
        "//errors",
        "//lib/nlohmann_json:json",
        "//picoboot_connection",
        "@libusb",
        "@pico-sdk//src/common/boot_picobin_headers",
        "@pico-sdk//src/common/boot_picoboot_headers",
        "@pico-sdk//src/common/boot_uf2_headers",
        "@pico-sdk//src/common/pico_base_headers",
        "@pico-sdk//src/common/pico_binary_info",
        "@pico-sdk//src/common/pico_usb_reset_interface_headers",
        "@pico-sdk//src/rp2350/hardware_regs:otp_data",
        "@pico-sdk//src/rp2_common/pico_bootrom:pico_bootrom_headers",
        "@pico-sdk//src/rp2_common/pico_stdio_usb:reset_interface_headers",
    ],
)
