#!/usr/bin/env python

Import("env")

import core_builders
from platform_methods import run_in_subprocess

env.core_sources = []


# Generate AES256 script encryption key
import os

txt = "0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0"
if "SCRIPT_AES256_ENCRYPTION_KEY" in os.environ:
    key = os.environ["SCRIPT_AES256_ENCRYPTION_KEY"]
    ec_valid = True
    if len(key) != 64:
        ec_valid = False
    else:
        txt = ""
        for i in range(len(key) >> 1):
            if i > 0:
                txt += ","
            txts = "0x" + key[i * 2 : i * 2 + 2]
            try:
                int(txts, 16)
            except Exception:
                ec_valid = False
            txt += txts
    if not ec_valid:
        print("Error: Invalid AES256 encryption key, not 64 hexadecimal characters: '" + key + "'.")
        print(
            "Unset 'SCRIPT_AES256_ENCRYPTION_KEY' in your environment "
            "or make sure that it contains exactly 64 hexadecimal characters."
        )
        Exit(255)

# NOTE: It is safe to generate this file here, since this is still executed serially
with open("script_encryption_key.gen.cpp", "w") as f:
    f.write('#include "core/config/project_settings.h"\nuint8_t script_encryption_key[32]={' + txt + "};\n")


# Add required thirdparty code.

thirdparty_obj = []

env_thirdparty = env.Clone()
env_thirdparty.disable_warnings()

# Misc thirdparty code: header paths are hardcoded, we don't need to append
# to the include path (saves a few chars on the compiler invocation for touchy MSVC...)
thirdparty_misc_dir = "thirdparty/misc/"
thirdparty_misc_sources = [
    # C sources
    "fastlz.c",
    # C++ sources
    "hq2x.cpp",
    "pcg.cpp",
    "triangulator.cpp",
    "clipper.cpp",
]
thirdparty_misc_sources = [thirdparty_misc_dir + file for file in thirdparty_misc_sources]
env_thirdparty.add_source_files(thirdparty_obj, thirdparty_misc_sources)

# Zlib library, can be unbundled
thirdparty_zlib_dir = "#core/thirdparty/zlib/"
thirdparty_zlib_sources = [
    "adler32.c",
    "compress.c",
    "crc32.c",
    "deflate.c",
    "infback.c",
    "inffast.c",
    "inflate.c",
    "inftrees.c",
    "trees.c",
    "uncompr.c",
    "zutil.c",
]
thirdparty_zlib_sources = [thirdparty_zlib_dir + file for file in thirdparty_zlib_sources]

env_thirdparty.Prepend(CPPPATH=[thirdparty_zlib_dir])
# Needs to be available in main env too
env.Prepend(CPPPATH=[thirdparty_zlib_dir])
if env["target"] == "debug":
    env_thirdparty.Append(CPPDEFINES=["ZLIB_DEBUG"])

env_thirdparty.add_source_files(thirdparty_obj, thirdparty_zlib_sources)

env.core_sources += thirdparty_obj

#if env["scu_build"]:
#    has_mbedtls_module = False
#
#    try:
#        has_mbedtls_module = env["module_mbedtls_enabled"]
#    except:
#        pass
#
#    if env["builtin_mbedtls"] and not has_mbedtls_module:
#        env.Prepend(CPPPATH=["crypto/mbedtls/include"])
#
#    if env["builtin_mbedtls"] and has_mbedtls_module:
#        env.Prepend(CPPPATH=["#modules/mbedtls/mbedtls/include"])

# Pandemonium source files

env.add_source_files(env.core_sources, "*.cpp")
env.add_source_files(env.core_sources, "script_encryption_key.gen.cpp")
env.add_source_files(env.core_sources, "version_hash.gen.cpp")

# Authors
env.Depends("#core/authors.gen.h", "../AUTHORS.md")
env.CommandNoCache("#core/authors.gen.h", "../AUTHORS.md", run_in_subprocess(core_builders.make_authors_header))

# Donors
env.Depends("#core/donors.gen.h", "../DONORS.md")
env.CommandNoCache("#core/donors.gen.h", "../DONORS.md", run_in_subprocess(core_builders.make_donors_header))

license_files = [ "../LICENSE.txt", "../COPYRIGHT.txt" ]
license_files.extend(env.module_license_files)

# License
env.Depends("#core/license.gen.h", license_files)
env.CommandNoCache(
    "#core/license.gen.h", license_files, run_in_subprocess(core_builders.make_license_header)
)

# Chain load SCsubs
SConscript("os/SCsub")
SConscript("math/SCsub")
SConscript("string/SCsub")
SConscript("containers/SCsub")
SConscript("variant/SCsub")
SConscript("error/SCsub")
SConscript("config/SCsub")
SConscript("crypto/SCsub")
SConscript("io/SCsub")
SConscript("log/SCsub")
SConscript("object/SCsub")
SConscript("input/SCsub")
SConscript("bind/SCsub")

# Build it all as a library
lib = env.add_library("core", env.core_sources)
env.Prepend(LIBS=[lib])

# Needed to force rebuilding the core files when the thirdparty code is updated.
env.Depends(lib, thirdparty_obj)
