using BinaryBuilder, Pkg

name    = "TypeDBDriverClib"   # BinaryBuilder appends _jll → TypeDBDriverClib_jll
version = v"3.8.1"

sources = [
    GitSource(
        "https://github.com/typedb/typedb-driver.git",
        "8e8d4a43da32adc1c56084f4d34174bebd0ce34a",  # tag 3.8.1
    ),
]

script = raw"""
cd ${WORKSPACE}/srcdir/typedb-driver

# c/Cargo.toml (auto-generated by TypeDB's Bazel sync tool) does not declare
# crate-type = ["cdylib"].  Patch it in-place so that `cargo build` produces
# a C-ABI shared library (.dylib/.so/.dll).
sed -i 's/path = "src\/lib.rs"/path = "src\/lib.rs"\ncrate-type = ["cdylib"]/' c/Cargo.toml

# typedb-protocol (a git dependency) has a build.rs that calls tonic_build
# which invokes protoc.  Make the host protoc binary visible to prost-build.
export PROTOC=$(which protoc)

# BinaryBuilder sets `rust_target` for cross-compilation.
cargo build --release -p typedb_driver_clib

install -Dvm 755 "target/${rust_target}/release"/*typedb_driver_clib.${dlext} -t  "${libdir}"
"""

platforms = [
    Platform("x86_64",  "linux";   libc="glibc"),
    Platform("aarch64", "linux";   libc="glibc"),
    Platform("x86_64",  "macos"),
    Platform("aarch64", "macos"),
    Platform("x86_64",  "windows"),
]

products = [
    LibraryProduct(["libtypedb_driver_clib", "typedb_driver_clib"], :libtypedb_driver_clib),
]

dependencies = [
    # typedb-protocol/grpc/rust/build.rs calls tonic_build::compile_protos(),
    # which invokes `protoc` at build time to generate Rust gRPC stubs.
    HostBuildDependency("protoc_jll"),
]

build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies;
               compilers             = [:c, :rust],
               julia_compat          = "1.6",
               preferred_gcc_version = v"5")
