#! /usr/bin/env python
import platform

windows_system = platform.system().lower() == "windows"

# Inherit the parent construction environment
Import("env", "compile_cpp", "link_exe")

# Clang-tidy compilation database for linting
compilation_database = env.CompilationDatabase()
clang_tidy = env.Command(
    target=["fixes.yaml"],
    source=[compilation_database, "cmd_line_arguments.cpp", "logging.cpp", "spade_object.cpp", "spade.cpp"],
    action=["clang-tidy -p ${SOURCES[0].dir} --export-fixes=${TARGETS[0]} ${SOURCES[1:]}"],
)
env.Alias("clang-tidy", clang_tidy)

# Build static objects
objects = []
env.MergeFlags("-I.")
objects.extend(env.Object("cmd_line_arguments.cpp"))
objects.extend(env.Object("logging.cpp"))
objects.extend(env.Object("spade_object.cpp", CXXFLAGS=env["ABAQUSCXXFLAGS"]))

# Write build abaqus environment file
object_string = " ".join(target.name for target in objects)
template_substitution = {
    "CXX": env["CXX"],
    "ABAQUSCXXFLAGS": env["ABAQUSCXXFLAGS"],
    "objects": object_string,
}
abaqus_environment = env.Substfile(
    "abaqus_v6.env.in",
    SUBST_DICT={
        "@compile_cpp@": compile_cpp.safe_substitute(template_substitution),
        "@link_exe@": link_exe.safe_substitute(template_substitution),
    },
)

# Build executable with Abaqus make
executable = "spade.exe" if windows_system else "spade"
spade_executable = env.Command(
    target=[executable],
    source=["spade.cpp", *objects, abaqus_environment],
    action=["cd ${TARGET.dir.abspath} && ${ABAQUS_PROGRAM} make job=${SOURCES[0].name}"],
)
env.Default(spade_executable)
if env["recompile"]:
    env.AlwaysBuild(spade_executable)
