# 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

name = "fmusim"
version = v"0.0.39001"

# Collection of sources required to complete build
sources = [
    GitSource("https://github.com/modelica/Reference-FMUs.git",
              "c8d4e6d90fa14be49d7622badf30e38eebea5e0a"),
    # fmusim compiles three minizip sources (ioapi.c, unzip.c, iowin32.c)
    # directly from a zlib source tree, so we ship one alongside.
    GitSource("https://github.com/madler/zlib.git",
              "da607da739fa6047df13e66a2af6b8bec7c2a498"),
    DirectorySource("./bundled"),
]

# Bash recipe for building across all platforms
script = raw"""
cd ${WORKSPACE}/srcdir/Reference-FMUs*/
atomic_patch -p1 ${WORKSPACE}/srcdir/patches/use-shared-deps.patch
# MinGW cross-compilation: Linux is case-sensitive, fix Windows header capitalization
find . \( -name "*.c" -o -name "*.h" \) -exec sed -i \
    -e 's/#include <Windows\.h>/#include <windows.h>/g' \
    -e 's/#include <Shlwapi\.h>/#include <shlwapi.h>/g' \
    {} \;

mkdir -p build && cd build
# Configure fmusim's own CMakeLists.txt directly (it has its own project() call)
# rather than the root, which would otherwise force -DFMI_VERSION=3 just to
# satisfy the reference-FMU model configure step. fmusim itself always
# compiles support for FMI 1/2/3.
cmake \
    -DCMAKE_INSTALL_PREFIX=${prefix} \
    -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TARGET_TOOLCHAIN} \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_C_STANDARD=99 \
    -DCMAKE_PREFIX_PATH=${prefix} \
    -DFMUSIM_VERSION=${version} \
    -DZLIB_SRC_DIR=${WORKSPACE}/srcdir/zlib \
    ../fmusim

cmake --build . --parallel ${nproc}

install -Dvm 755 fmusim${exeext} ${bindir}/fmusim${exeext}
install_license ../LICENSE.txt
"""

# Upstream supports only x86_64 / aarch64 on linux/macos/windows.
platforms = filter(supported_platforms()) do p
    os(p) in ("linux", "macos", "windows") &&
        arch(p) in ("x86_64", "aarch64") &&
        libc(p) != "musl"
end

# The products that we will ensure are always built
products = [
    ExecutableProduct("fmusim", :fmusim),
]

# Dependencies that must be installed before this package can be built
dependencies = [
    Dependency("XML2_jll"),
    Dependency("Zlib_jll"),
    Dependency("Sundials_jll"; compat="7.4"),
]

# Build the tarballs, and possibly a `build.jl` as well.
build_tarballs(ARGS, name, version, sources, script, platforms, products, dependencies;
               julia_compat="1.6", preferred_gcc_version=v"9")
