# Note that this script can accept some limited command-line arguments, run
# `julia build_tarballs.jl --help` to see a usage message.
using BinaryBuilder, Pkg

const YGGDRASIL_DIR = "../.."
include(joinpath(YGGDRASIL_DIR, "platforms", "macos_sdks.jl"))

name = "z3"
version = v"5.0.0"

# Collection of sources required to complete build
sources = [
    ArchiveSource("https://github.com/Z3Prover/z3/releases/download/z3-$(version)/z3_solver-$(version).0.tar.gz",
                  "24d4b524c21f48c86c7058a36e83091c1fc08be28b68bf5a0f3cce5305ed8464"),
    DirectorySource("bundled"),
]

# Bash recipe for building across all platforms
script = raw"""
cd $WORKSPACE/srcdir/z3*/core

# Reported in <https://github.com/Z3Prover/z3/issues/10171>
atomic_patch -p1 $WORKSPACE/srcdir/patches/mingw-dbghelp.patch

# Patches Z3 to work around https://github.com/ahumenberger/Z3.jl/issues/28
patch -p0 <<EOD
--- src/util/memory_manager.cpp 2024-03-07 11:10:51
+++ src/util/memory_manager.cpp 2024-06-12 17:45:50
@@ -28,6 +28,7 @@
 # define HAS_MALLOC_USABLE_SIZE
 # define malloc_usable_size _msize
 #endif
+#undef HAS_MALLOC_USABLE_SIZE

 // The following two function are automatically generated by the mk_make.py script.
 // The script collects ADD_INITIALIZER and ADD_FINALIZER commands in the .h files.
EOD

cmake -B build \
    -DCMAKE_INSTALL_PREFIX=${prefix} \
    -DCMAKE_FIND_ROOT_PATH="${prefix}" \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
    -DZ3_USE_LIB_GMP=True \
    -DZ3_BUILD_JULIA_BINDINGS=True \
    -DZ3_ENABLE_EXAMPLE_TARGETS=False \
    -DJulia_PREFIX="${prefix}"
cmake --build build --parallel ${nproc}
cmake --install build
install_license LICENSE.txt
"""

# Use SDK 14.5 for C++20 support
sources, script = require_macos_sdk("14.5", sources, script)

# These are the platforms we will build for by default, unless further
# platforms are passed in on the command line
include("../../L/libjulia/common.jl")
platforms = vcat(libjulia_platforms.(julia_versions)...)
platforms = expand_cxxstring_abis(platforms)

# The products that we will ensure are always built
products = [
    LibraryProduct("libz3", :libz3),
    LibraryProduct("libz3jl", :libz3jl),
    ExecutableProduct("z3", :z3)
]

# Dependencies that must be installed before this package can be built
dependencies = [
    BuildDependency("libjulia_jll"),
    Dependency("GMP_jll"),
    Dependency("libcxxwrap_julia_jll"; compat="0.14.9"),
    Dependency("CompilerSupportLibraries_jll"; platforms=filter(!Sys.isapple, platforms)),
]

# Use GCC 13 for C++20 support
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies;
               julia_compat="1.10", preferred_gcc_version=v"13")
