# pylint: disable=E0602
# fmt: off

import os
import tools, models, ui
import random

BITCOIN_ONLY = ARGUMENTS.get('BITCOIN_ONLY', '0')
PRODUCTION = ARGUMENTS.get('PRODUCTION', '0') == '1'
BOOTLOADER_QA = ARGUMENTS.get('BOOTLOADER_QA', '0') == '1'
BOOTLOADER_DEVEL = ARGUMENTS.get('BOOTLOADER_DEVEL', '0') == '1'
UNSAFE_FW = ARGUMENTS.get('UNSAFE_FW', '0') == '1'
EVERYTHING = BITCOIN_ONLY != '1'
TREZOR_MODEL = ARGUMENTS.get('TREZOR_MODEL', 'T2T1')
CMAKELISTS = int(ARGUMENTS.get('CMAKELISTS', 0))
PYOPT = ARGUMENTS.get('PYOPT', '1')
DISABLE_OPTIGA = ARGUMENTS.get('DISABLE_OPTIGA', '0') == '1'
DISABLE_TROPIC = ARGUMENTS.get('DISABLE_TROPIC', '0') == '1'
HW_REVISION = ARGUMENTS.get('HW_REVISION', None)
SCM_REVISION = ARGUMENTS.get('SCM_REVISION', None)
THP = ARGUMENTS.get('THP', '0') == '1' # Trezor-Host Protocol
BENCHMARK = ARGUMENTS.get('BENCHMARK', '0') == '1'
LOG_STACK_USAGE = ARGUMENTS.get('LOG_STACK_USAGE', '0') == '1'
MICROPY_ENABLE_SOURCE_LINE = ARGUMENTS.get('MICROPY_ENABLE_SOURCE_LINE', '0')
DISABLE_ANIMATION = ARGUMENTS.get('TREZOR_DISABLE_ANIMATION', '0') == '1'
BLOCK_ON_VCP = ARGUMENTS.get('BLOCK_ON_VCP', '0') == '1'
UI_PERFORMANCE_OVERLAY = ARGUMENTS.get('UI_PERFORMANCE_OVERLAY', '0') == '1'
DBG_CONSOLE = ARGUMENTS.get('DBG_CONSOLE', '')
EXTAPP_SUPPORT = ARGUMENTS.get('EXTAPP_SUPPORT', '0') == '1'

STORAGE_INSECURE_TESTING_MODE = ARGUMENTS.get('STORAGE_INSECURE_TESTING_MODE', '0') == '1'
if STORAGE_INSECURE_TESTING_MODE and PRODUCTION:
    raise RuntimeError("STORAGE_INSECURE_TESTING_MODE cannot be used in production")
if STORAGE_INSECURE_TESTING_MODE:
    DISABLE_OPTIGA = True
    DISABLE_TROPIC = True
    PYOPT = "0"

if BENCHMARK and PYOPT != '0':
  print("BENCHMARK=1 works only with PYOPT=0.")
  exit(1)

if LOG_STACK_USAGE and PYOPT != '0':
  print("LOG_STACK_USAGE=1 works only with PYOPT=0.")
  exit(1)

FEATURE_FLAGS = {
    "RDI": True,
    "SECP256K1_ZKP": True,  # required for trezor.crypto.curve.bip340 (BIP340/Taproot)
    "AES_GCM": BENCHMARK or THP,
}

FEATURES_WANTED = [
    "ble",
    "boot_ucb",
    "consumption_mask",
    "display",
    "dma2d",
    "haptic",
    "input",
    "ipc",
    "optiga",
    "power_manager",
    "rgb_led",
    "sd_card",
    "secmon_layout",
    "serial_number",
    "storage",
    "suspend",
    'telemetry',
    "tropic",
    "usb",
    "usb_iface_wire",
    ]

if DISABLE_OPTIGA:
    if PYOPT != '0':
        raise RuntimeError("DISABLE_OPTIGA requires PYOPT=0")
    FEATURES_WANTED.remove("optiga")

if DISABLE_TROPIC:
    if PRODUCTION:
        raise RuntimeError("DISABLE_TROPIC requires non-production build")
    FEATURES_WANTED.remove("tropic")

if PYOPT == '0':
    DBG_CONSOLE = DBG_CONSOLE or "VCP"
    FEATURES_WANTED += ["usb_iface_debug"]

if DBG_CONSOLE != "":
    FEATURES_WANTED += ["dbg_console"]

if TREZOR_MODEL in ['T3W1'] and EXTAPP_SUPPORT:
    FEATURES_WANTED += ["app_loading"]

CCFLAGS_MOD = ''
CPPPATH_MOD = []
CPPDEFINES_MOD = []
SOURCE_MOD = []
SOURCE_MOD_CRYPTO = []
CPPDEFINES_HAL = []
SOURCE_HAL = []
PATH_HAL = []
RUST_UI_FEATURES = []

FROZEN = True

# modtrezorconfig
CPPPATH_MOD += [
    'embed/upymod/modtrezorconfig',
]
SOURCE_MOD += [
    'embed/upymod/modtrezorconfig/modtrezorconfig.c',
]

# modtrezorcrypto
CCFLAGS_MOD += '-Wno-sequence-point '
CPPPATH_MOD += [
    'vendor/trezor-crypto',
]
CPPDEFINES_MOD += [
    'AES_128',
    'AES_192',
    ('USE_BIP32_CACHE', '0'),
    ('USE_KECCAK', '1'),
    ('USE_ETHEREUM', '1' if EVERYTHING else '0'),
    ('USE_MONERO', '1' if EVERYTHING else '0'),
    ('USE_CARDANO', '1' if EVERYTHING else '0'),
    ('USE_NEM', '1' if (EVERYTHING and TREZOR_MODEL == "T2T1") else '0'),
    ('USE_EOS', '1' if (EVERYTHING and TREZOR_MODEL == "T2T1") else '0'),
    ('MICROPY_ENABLE_SOURCE_LINE', MICROPY_ENABLE_SOURCE_LINE),
    ('DISABLE_ANIMATION', '1' if DISABLE_ANIMATION else '0'),
    ('LOG_STACK_USAGE', '1' if LOG_STACK_USAGE else '0'),
    ('BLOCK_ON_VCP', '1' if BLOCK_ON_VCP else '0'),
]
SOURCE_MOD += [
    'embed/upymod/trezorobj.c',
    'embed/upymod/modtrezorcrypto/crc.c',
    'embed/upymod/modtrezorcrypto/modtrezorcrypto.c',
]
SOURCE_MOD_CRYPTO += [
    'vendor/trezor-crypto/address.c',
    'vendor/trezor-crypto/aes/aes_modes.c',
    'vendor/trezor-crypto/aes/aesccm.c',
    'vendor/trezor-crypto/aes/aescrypt.c',
    'vendor/trezor-crypto/aes/aeskey.c',
    'vendor/trezor-crypto/aes/aestab.c',
    'vendor/trezor-crypto/base32.c',
    'vendor/trezor-crypto/base58.c',
    'vendor/trezor-crypto/bignum.c',
    'vendor/trezor-crypto/bip32.c',
    'vendor/trezor-crypto/bip39.c',
    'vendor/trezor-crypto/bip39_english.c',
    'vendor/trezor-crypto/blake256.c',
    'vendor/trezor-crypto/blake2b.c',
    'vendor/trezor-crypto/blake2s.c',
    'vendor/trezor-crypto/buffer.c',
    'vendor/trezor-crypto/chacha20poly1305/chacha20poly1305.c',
    'vendor/trezor-crypto/chacha20poly1305/chacha_merged.c',
    'vendor/trezor-crypto/chacha20poly1305/poly1305-donna.c',
    'vendor/trezor-crypto/chacha20poly1305/rfc7539.c',
    'vendor/trezor-crypto/chacha_drbg.c',
    'vendor/trezor-crypto/curves.c',
    'vendor/trezor-crypto/der.c',
    'vendor/trezor-crypto/ecdsa.c',
    'vendor/trezor-crypto/ed25519-donna/curve25519-donna-32bit.c',
    'vendor/trezor-crypto/ed25519-donna/curve25519-donna-helpers.c',
    'vendor/trezor-crypto/ed25519-donna/curve25519-donna-scalarmult-base.c',
    'vendor/trezor-crypto/ed25519-donna/ed25519-donna-32bit-tables.c',
    'vendor/trezor-crypto/ed25519-donna/ed25519-donna-basepoint-table.c',
    'vendor/trezor-crypto/ed25519-donna/ed25519-donna-impl-base.c',
    'vendor/trezor-crypto/ed25519-donna/ed25519-keccak.c',
    'vendor/trezor-crypto/ed25519-donna/ed25519-sha3.c',
    'vendor/trezor-crypto/ed25519-donna/ed25519.c',
    'vendor/trezor-crypto/ed25519-donna/modm-donna-32bit.c',
    'vendor/trezor-crypto/groestl.c',
    'vendor/trezor-crypto/hasher.c',
    'vendor/trezor-crypto/hmac.c',
    'vendor/trezor-crypto/hmac_drbg.c',
    'vendor/trezor-crypto/memzero.c',
    'vendor/trezor-crypto/nem.c',
    'vendor/trezor-crypto/nist256p1.c',
    'vendor/trezor-crypto/pbkdf2.c',
    'vendor/trezor-crypto/rand.c',
    'vendor/trezor-crypto/rfc6979.c',
    'vendor/trezor-crypto/ripemd160.c',
    'vendor/trezor-crypto/secp256k1.c',
    'vendor/trezor-crypto/segwit_addr.c',
    'vendor/trezor-crypto/sha2.c',
    'vendor/trezor-crypto/sha3.c',
    'vendor/trezor-crypto/shamir.c',
    'vendor/trezor-crypto/slip39.c',
    'vendor/trezor-crypto/slip39_english.c',
    'vendor/trezor-crypto/tls_prf.c',
]
if EVERYTHING:
    SOURCE_MOD_CRYPTO += [
        'vendor/trezor-crypto/cardano.c',
        'vendor/trezor-crypto/monero/base58.c',
        'vendor/trezor-crypto/monero/serialize.c',
        'vendor/trezor-crypto/monero/xmr.c',
    ]

# libsecp256k1-zkp
if FEATURE_FLAGS["SECP256K1_ZKP"]:
    CPPPATH_MOD += [
        'vendor/secp256k1-zkp',
        'vendor/secp256k1-zkp/src',
        'vendor/secp256k1-zkp/include',
    ]
    CPPDEFINES_MOD += [
        'USE_SECP256K1_ZKP',
        'USE_SECP256K1_ZKP_ECDSA',
        ('SECP256K1_CONTEXT_SIZE', '180'),
        'USE_ASM_ARM',
        'USE_EXTERNAL_ASM',
        'USE_EXTERNAL_DEFAULT_CALLBACKS',
        ('ECMULT_GEN_PREC_BITS', '2'),
        ('ECMULT_WINDOW_SIZE', '2'),
        'ENABLE_MODULE_GENERATOR',
        'ENABLE_MODULE_RECOVERY',
        'ENABLE_MODULE_SCHNORRSIG',
        'ENABLE_MODULE_EXTRAKEYS',
        'ENABLE_MODULE_ECDH',
    ]
    SOURCE_MOD_SECP256K1_ZKP = [
        'vendor/secp256k1-zkp/src/secp256k1.c',
        'vendor/secp256k1-zkp/src/precomputed_ecmult.c',
        'vendor/secp256k1-zkp/src/precomputed_ecmult_gen.c',
        'vendor/secp256k1-zkp/src/asm/field_10x26_arm.s'
    ]
    SOURCE_MOD_CRYPTO += [
        'vendor/trezor-crypto/zkp_context.c',
        'vendor/trezor-crypto/zkp_ecdsa.c',
        'vendor/trezor-crypto/zkp_bip340.c',
    ]

# AES-GCM
if FEATURE_FLAGS["AES_GCM"]:
    CPPDEFINES_MOD += [
        'USE_AES_GCM',
        'AES_VAR',
    ]
    SOURCE_MOD_CRYPTO += [
        'vendor/trezor-crypto/aes/gf128mul.c',
        'vendor/trezor-crypto/aes/aesgcm.c',
    ]

# modtrezorio
SOURCE_MOD += [
    'embed/upymod/modtrezorio/modtrezorio.c',
]

# modtrezorui
CPPPATH_MOD += [
        'vendor/micropython/lib/uzlib',
]
SOURCE_MOD += [
    'embed/upymod/modtrezorui/modtrezorui.c',
    'embed/io/display/display_utils.c',
    'embed/io/gfx/bitblt/gfx_bitblt.c',
    'embed/io/gfx/bitblt/gfx_bitblt_rgb565.c',
    'embed/io/gfx/bitblt/gfx_bitblt_rgba8888.c',
    'embed/io/gfx/bitblt/gfx_bitblt_mono8.c',
    'embed/io/gfx/gfx_color.c',
    'embed/io/gfx/gfx_draw.c',
    'embed/io/gfx/rsod.c',
    'embed/io/gfx/terminal/font_bitmap.c',
    'embed/io/gfx/terminal/terminal.c',
    'embed/io/translations/translations.c',
    'embed/rtl/error_handling.c',
    'embed/rtl/scm_revision.c',
    'embed/rtl/strutils.c',
    'embed/sec/image/boot_image_embdata.c',
    'embed/sec/image/image.c',
    'vendor/micropython/lib/uzlib/adler32.c',
    'vendor/micropython/lib/uzlib/crc32.c',
    'vendor/micropython/lib/uzlib/tinflate.c',
]

if not PRODUCTION:
    SOURCE_MOD += ['embed/rtl/printf.c']

if "app_loading" in FEATURES_WANTED:
    SOURCE_MOD += [
        'embed/api/trezor_api_v1_impl.c',
        'embed/upymod/modtrezorapp/modtrezorapp.c',
    ]


CPPDEFINES_MOD += [
    'TRANSLATIONS',
    'FANCY_FATAL_ERROR',
    ]

if TREZOR_MODEL in ["T3W1", "T3T1"]:
    CPPDEFINES_MOD += ('THREAD_LOCAL', '__attribute__((section(".tls")))'),

# modtrezorutils
SOURCE_MOD += [
    'embed/upymod/modtrezorutils/modtrezorutils.c',
]

# rust mods
SOURCE_MOD += [
    'embed/upymod/rustmods.c',
]

# modutime
SOURCE_MOD += [
    'embed/upymod/modutime.c',
]

SOURCE_MICROPYTHON = [
    'vendor/micropython/extmod/modubinascii.c',
    'vendor/micropython/extmod/moductypes.c',
    'vendor/micropython/extmod/moduheapq.c',
    'vendor/micropython/extmod/modutimeq.c',
    'vendor/micropython/extmod/utime_mphal.c',
    'vendor/micropython/shared/libc/abort_.c',
    'vendor/micropython/shared/libc/printf.c',
    'vendor/micropython/shared/runtime/gchelper_m3.s',
    'vendor/micropython/shared/runtime/gchelper_native.c',
    'vendor/micropython/shared/runtime/interrupt_char.c',
    'vendor/micropython/shared/runtime/pyexec.c',
    'vendor/micropython/shared/runtime/stdout_helpers.c',
    'vendor/micropython/shared/timeutils/timeutils.c',
    'vendor/micropython/ports/stm32/gccollect.c',
    'vendor/micropython/py/argcheck.c',
    'vendor/micropython/py/asmarm.c',
    'vendor/micropython/py/asmbase.c',
    'vendor/micropython/py/asmthumb.c',
    'vendor/micropython/py/asmx64.c',
    'vendor/micropython/py/asmx86.c',
    'vendor/micropython/py/asmxtensa.c',
    'vendor/micropython/py/bc.c',
    'vendor/micropython/py/binary.c',
    'vendor/micropython/py/builtinevex.c',
    'vendor/micropython/py/builtinhelp.c',
    'vendor/micropython/py/builtinimport.c',
    'vendor/micropython/py/compile.c',
    'vendor/micropython/py/emitbc.c',
    'vendor/micropython/py/emitcommon.c',
    'vendor/micropython/py/emitglue.c',
    'vendor/micropython/py/emitinlinethumb.c',
    'vendor/micropython/py/emitinlinextensa.c',
    'vendor/micropython/py/formatfloat.c',
    'vendor/micropython/py/frozenmod.c',
    'vendor/micropython/py/lexer.c',
    'vendor/micropython/py/malloc.c',
    'vendor/micropython/py/map.c',
    'vendor/micropython/py/modarray.c',
    'vendor/micropython/py/modbuiltins.c',
    'vendor/micropython/py/modgc.c',
    'vendor/micropython/py/modmath.c',
    'vendor/micropython/py/modmicropython.c',
    'vendor/micropython/py/modstruct.c',
    'vendor/micropython/py/modsys.c',
    'vendor/micropython/py/mpprint.c',
    'vendor/micropython/py/mpstate.c',
    'vendor/micropython/py/mpz.c',
    'vendor/micropython/py/nativeglue.c',
    'vendor/micropython/py/obj.c',
    'vendor/micropython/py/objarray.c',
    'vendor/micropython/py/objattrtuple.c',
    'vendor/micropython/py/objbool.c',
    'vendor/micropython/py/objboundmeth.c',
    'vendor/micropython/py/objcell.c',
    'vendor/micropython/py/objclosure.c',
    'vendor/micropython/py/objcomplex.c',
    'vendor/micropython/py/objdict.c',
    'vendor/micropython/py/objenumerate.c',
    'vendor/micropython/py/objexcept.c',
    'vendor/micropython/py/objfilter.c',
    'vendor/micropython/py/objfloat.c',
    'vendor/micropython/py/objfun.c',
    'vendor/micropython/py/objgenerator.c',
    'vendor/micropython/py/objgetitemiter.c',
    'vendor/micropython/py/objint.c',
    'vendor/micropython/py/objint_longlong.c',
    'vendor/micropython/py/objint_mpz.c',
    'vendor/micropython/py/objlist.c',
    'vendor/micropython/py/objmap.c',
    'vendor/micropython/py/objmodule.c',
    'vendor/micropython/py/objnamedtuple.c',
    'vendor/micropython/py/objnone.c',
    'vendor/micropython/py/objobject.c',
    'vendor/micropython/py/objpolyiter.c',
    'vendor/micropython/py/objproperty.c',
    'vendor/micropython/py/objrange.c',
    'vendor/micropython/py/objreversed.c',
    'vendor/micropython/py/objset.c',
    'vendor/micropython/py/objsingleton.c',
    'vendor/micropython/py/objslice.c',
    'vendor/micropython/py/objstr.c',
    'vendor/micropython/py/objstringio.c',
    'vendor/micropython/py/objstrunicode.c',
    'vendor/micropython/py/objtuple.c',
    'vendor/micropython/py/objtype.c',
    'vendor/micropython/py/objzip.c',
    'vendor/micropython/py/opmethods.c',
    'vendor/micropython/py/pairheap.c',
    'vendor/micropython/py/parse.c',
    'vendor/micropython/py/parsenum.c',
    'vendor/micropython/py/parsenumbase.c',
    'vendor/micropython/py/persistentcode.c',
    'vendor/micropython/py/qstr.c',
    'vendor/micropython/py/reader.c',
    'vendor/micropython/py/repl.c',
    'vendor/micropython/py/runtime.c',
    'vendor/micropython/py/runtime_utils.c',
    'vendor/micropython/py/scheduler.c',
    'vendor/micropython/py/scope.c',
    'vendor/micropython/py/sequence.c',
    'vendor/micropython/py/showbc.c',
    'vendor/micropython/py/smallint.c',
    'vendor/micropython/py/stackctrl.c',
    'vendor/micropython/py/stream.c',
    'vendor/micropython/py/unicode.c',
    'vendor/micropython/py/vstr.c',
    'vendor/micropython/py/warning.c',
]

SOURCE_MICROPYTHON_SPEED = [
    'vendor/micropython/py/gc.c',
    'vendor/micropython/py/pystack.c',
    'vendor/micropython/py/vm.c',
]

if FEATURE_FLAGS["RDI"]:
    CPPDEFINES_MOD += ['RDI']

TRANSLATION_DATA = [
    "translations/en.json",
    "translations/order.json",
]

if THP:
    CPPDEFINES_MOD += ['USE_THP']
    SOURCE_MOD += [
        'vendor/trezor-crypto/elligator2.c',
    ]

if STORAGE_INSECURE_TESTING_MODE:
    CPPDEFINES_MOD += ['STORAGE_INSECURE_TESTING_MODE']

ui.init_ui(TREZOR_MODEL, "firmware", RUST_UI_FEATURES)

SOURCE_QSTR = SOURCE_MOD + SOURCE_MICROPYTHON + SOURCE_MICROPYTHON_SPEED

if PYOPT == '0':
    DEBUG_FLAGS = "-DMICROPY_OOM_CALLBACK=1 -DSTATIC="
else:
    DEBUG_FLAGS = "-DMICROPY_OOM_CALLBACK=0"

env = Environment(
    ENV=os.environ,
    CFLAGS=(
        f"{ARGUMENTS.get('CFLAGS', '')} -DPRODUCTION={int(PRODUCTION)} -DPYOPT={PYOPT} "
        f"-DBOOTLOADER_QA={int(BOOTLOADER_QA)} -DBITCOIN_ONLY={BITCOIN_ONLY} {DEBUG_FLAGS}"
    ),
    CPPDEFINES_IMPLICIT=[],
    CPPDEFPREFIX="-D'",
    CPPDEFSUFFIX="'",
    DBG_CONSOLE=DBG_CONSOLE,
    )

FEATURES_AVAILABLE = models.configure_board(TREZOR_MODEL, HW_REVISION, FEATURES_WANTED, env, CPPDEFINES_HAL, SOURCE_HAL, PATH_HAL)

SOURCE_FIRMWARE = [
    'embed/projects/firmware/header.S',
    'embed/projects/firmware/main.c',
    'embed/projects/firmware/mphalport.c',
    'embed/projects/firmware/nlrthumb.c',
]

SDCARD = ('sd_card' in FEATURES_AVAILABLE)
SERIAL_NUMBER = ('serial_number' in FEATURES_AVAILABLE)

env.Tool('micropython')

env.Replace(
    CAT='cat',
    DD='dd',
    CP='cp',
    SED='sed',
    AS='arm-none-eabi-as',
    AR='arm-none-eabi-ar',
    CC='arm-none-eabi-gcc',
    LINK='arm-none-eabi-gcc',
    SIZE='arm-none-eabi-size',
    STRIP='arm-none-eabi-strip',
    OBJCOPY='arm-none-eabi-objcopy', )

env.Replace(
    TREZOR_MODEL=TREZOR_MODEL,)

ALLPATHS = [
        '.',
        'embed/api',
        'embed/rust',
        'embed/projects/firmware',
        'embed/rtl/inc',
        'embed/models',
        'embed/io/gfx/inc',
        'embed/io/translations/inc',
        'embed/sys/bsp/inc',
        'embed/sec/image/inc',
        'embed/sec/rsod/inc',
        'embed/upymod/modtrezorui',
        'vendor/micropython',
    ] + CPPPATH_MOD + PATH_HAL

env.Replace(
    COPT=env.get('ENV').get('OPTIMIZE', '-Os'),
    CCFLAGS='$COPT '
    '-g3 '
    '-nostdlib '
    '-std=gnu11 -Wall -Werror -Wdouble-promotion -Wpointer-arith -Wno-missing-braces -fno-common '
    '-fsingle-precision-constant -fdata-sections -ffunction-sections '
    '-fstack-protector-all '
    +  env.get('ENV')["CPU_CCFLAGS"] + CCFLAGS_MOD,
    CCFLAGS_QSTR='-DNO_QSTR -DN_X64 -DN_X86 -DN_THUMB',
    LINKFLAGS=[f'-Tbuild/firmware/{env.get("ENV")["MEMORY_LAYOUT"]}', '-Wl,--gc-sections', '-Wl,--print-memory-usage', '-Wl,-Map=build/firmware/firmware.map', '-Wl,--warn-common'],
    CPPPATH=ALLPATHS,
    CPPDEFINES=[
        'FIRMWARE',
        'TREZOR_MODEL_'+TREZOR_MODEL,
        'USE_HAL_DRIVER',
        'ARM_USER_MODE',
        ui.get_ui_layout(TREZOR_MODEL),
    ] + CPPDEFINES_MOD + CPPDEFINES_HAL,
    ASFLAGS=env.get('ENV')['CPU_ASFLAGS'],
    ASPPFLAGS='$CFLAGS $CCFLAGS',
    )

BYTECODE_OPTIMIZATION = {'0': '0', '1': '3'}[PYOPT]

env.Replace(
    HEADERTOOL='headertool',
    PYTHON='python',
    MAKECOMPRESSEDDATA='$PYTHON vendor/micropython/py/makecompresseddata.py',
    MAKEQSTRDATA='$PYTHON vendor/micropython/py/makeqstrdata.py',
    MAKEVERSIONHDR='$PYTHON vendor/micropython/py/makeversionhdr.py',
    MAKEMODULEDEFS='$PYTHON vendor/micropython/py/makemoduledefs.py',
    MAKECMAKELISTS='$PYTHON tools/make_cmakelists.py',
    MPY_TOOL='$PYTHON vendor/micropython/tools/mpy-tool.py',
    MPY_CROSS='vendor/micropython/mpy-cross/mpy-cross -O' + BYTECODE_OPTIMIZATION,
    PB2PY='$PYTHON ../common/protob/pb2py',
)

#
# Qstrings
#

PROTO_SOURCES_DIR = '../../../common/protob/'

exclude_list = [PROTO_SOURCES_DIR + 'messages-bootloader.proto']
if not THP:
    exclude_list.append(PROTO_SOURCES_DIR + 'messages-thp.proto')
if PYOPT != '0':
    exclude_list.append(PROTO_SOURCES_DIR + 'messages-debug.proto')

PROTO_SOURCES = Glob(PROTO_SOURCES_DIR + '*.proto',
    exclude=exclude_list
)

qstr_protobuf = env.Command(
    target=[
        'genhdr/qstrdefs.protobuf.h',
    ],
    source=PROTO_SOURCES,
    action='$PB2PY $SOURCES --qstr-out ${TARGET} --bitcoin-only=%s' % BITCOIN_ONLY,
)

qstr_micropython = 'vendor/micropython/py/qstrdefs.h'

qstr_extra = 'embed/upymod/qstrdefsport.h'

micropy_defines = env.MicroPyDefines(source=SOURCE_QSTR)

qstr_collected = env.CollectQstr(
    target='genhdr/qstrdefs.collected.h', source=micropy_defines)

qstr_preprocessed = env.PreprocessQstr(
    target='genhdr/qstrdefs.preprocessed.h',
    source=[qstr_micropython, qstr_protobuf, qstr_collected, qstr_extra])

qstr_generated = env.GenerateQstrDefs(
    target='genhdr/qstrdefs.generated.h', source=qstr_preprocessed)

env.Ignore(qstr_collected, qstr_generated)

#
# Micropython module declarations
#

moduledefs_collected = env.CollectModules(
    target='genhdr/moduledefs.collected.h', source=micropy_defines)

hdr_moduledefs = env.Command(
    target='genhdr/moduledefs.h',
    source=moduledefs_collected,
    action='$MAKEMODULEDEFS $SOURCE > $TARGET', )

env.Ignore(micropy_defines, micropy_defines)
env.Ignore(micropy_defines, qstr_generated)
env.Ignore(micropy_defines, hdr_moduledefs)

#
# Compressed Qstrings
#

compressed_collected = env.CollectCompressed(
    target='genhdr/compressed.collected', source=micropy_defines)

compressed_data = env.GenerateCompressed(
    target='genhdr/compressed.data.h', source=compressed_collected)

env.Ignore(micropy_defines, compressed_data)

#
# Micropython version
#

hdr_version = env.Command(
    target='genhdr/mpversion.h',
    source='',
    action='$MAKEVERSIONHDR $TARGET', )

env.Ignore(hdr_moduledefs, hdr_moduledefs)
env.Ignore(hdr_moduledefs, qstr_collected)
env.Ignore(hdr_moduledefs, qstr_preprocessed)
env.Ignore(hdr_moduledefs, qstr_generated)

#
# Frozen modules
#

if FROZEN:
    SOURCE_PY_DIR = 'src/'

    SOURCE_PY = Glob(SOURCE_PY_DIR + '*.py',
        exclude=[
            SOURCE_PY_DIR + 'ble.py',
        ] if "ble" not in FEATURES_AVAILABLE else []
    )
    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/*.py',
        exclude=[
            SOURCE_PY_DIR + 'trezor/sdcard.py',
        ] if not SDCARD else []
    ))
    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/crypto/*.py'))
    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/ui/*.py'))

    # UI layouts - common files and then model-specific. Exclude FIDO when BTC-only.
    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/ui/layouts/*.py',
        exclude=[
            SOURCE_PY_DIR + 'trezor/ui/layouts/fido.py',
        ] if not EVERYTHING else []
    ))

    layout_path = ui.get_ui_layout_path(TREZOR_MODEL)

    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + layout_path + '*.py',
        exclude=[
            SOURCE_PY_DIR + layout_path + 'fido.py',
        ] if not EVERYTHING else []
    ))

    if THP:
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/wire/thp/*.py'))
    if not THP or PYOPT == '0':
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/wire/codec/*.py'))

    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/wire/*.py',
        exclude=[
            SOURCE_PY_DIR + 'trezor/wire/wire_log.py'
        ] if PYOPT != '0' else []
    ))

    if 'power_manager' in FEATURES_AVAILABLE:
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/power_management/*.py'))

    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'storage/*.py',
        exclude=(
            ([SOURCE_PY_DIR + 'storage/sd_salt.py'] if not SDCARD else []) +
            ([SOURCE_PY_DIR + 'storage/debug.py'] if PYOPT != '0' else []) +
            ([
                SOURCE_PY_DIR + 'storage/cache_codec.py',
                SOURCE_PY_DIR + 'storage/cache_codec_keys.py'
            ] if THP and PYOPT != '0' else []) +
            ([
                SOURCE_PY_DIR + 'storage/cache_thp.py',
                SOURCE_PY_DIR + 'storage/cache_thp_keys.py'
            ] if not THP else [])
        )
    ))

    SOURCE_PY_DEBUG_ENUMS = [SOURCE_PY_DIR + 'trezor/enums/Debug*.py']
    SOURCE_PY_THP_ENUMS = [SOURCE_PY_DIR + 'trezor/enums/Thp*.py']
    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/*.py',
        exclude=[
            SOURCE_PY_DIR + 'trezor/enums/Cardano*.py',
            SOURCE_PY_DIR + 'trezor/enums/DebugMonero*.py',
            SOURCE_PY_DIR + 'trezor/enums/DefinitionType.py',
            SOURCE_PY_DIR + 'trezor/enums/Eos*.py',
            SOURCE_PY_DIR + 'trezor/enums/Ethereum*.py',
            SOURCE_PY_DIR + 'trezor/enums/Monero*.py',
            SOURCE_PY_DIR + 'trezor/enums/NEM*.py',
            SOURCE_PY_DIR + 'trezor/enums/Ripple*.py',
            SOURCE_PY_DIR + 'trezor/enums/Solana*.py',
            SOURCE_PY_DIR + 'trezor/enums/Stellar*.py',
            SOURCE_PY_DIR + 'trezor/enums/Tezos*.py',
            SOURCE_PY_DIR + 'trezor/enums/Zcash*.py',
            SOURCE_PY_DIR + 'trezor/enums/Tron*.py'
        ] + (
            SOURCE_PY_DEBUG_ENUMS if PYOPT != '0' else []
        ) + (
            SOURCE_PY_THP_ENUMS if not THP else []
        )
    ))

    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/*.py'))
    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/common/*.py',
        exclude=[
            SOURCE_PY_DIR + 'apps/common/definitions.py',
            SOURCE_PY_DIR + 'apps/common/definitions_constants.py',
        ] + (
            [SOURCE_PY_DIR + 'apps/common/sdcard.py'] if not SDCARD else []
        )
    ))
    if PYOPT == '0':
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/debug/*.py'))
    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/homescreen/*.py',
        exclude=[
            SOURCE_PY_DIR + 'apps/homescreen/device_menu.py',
        ] if TREZOR_MODEL != "T3W1" else [])
    )
    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/management/*.py',
        exclude=(
            ([SOURCE_PY_DIR + 'apps/management/sd_protect.py'] if not SDCARD else []) +
            ([SOURCE_PY_DIR + 'apps/management/get_serial_number.py'] if not SERIAL_NUMBER else [])
        )
    ))
    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/management/*/*.py',
        exclude=(
            ([SOURCE_PY_DIR + 'apps/management/ble/*.py'] if "ble" not in FEATURES_AVAILABLE else [])
        ))
    )
    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/misc/*.py'))
    if 'telemetry' in FEATURES_AVAILABLE:
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/telemetry/*.py'))
    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/bitcoin/*.py'))
    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/bitcoin/*/*.py',
        exclude=[
            SOURCE_PY_DIR + 'apps/bitcoin/sign_tx/decred.py',
            SOURCE_PY_DIR + 'apps/bitcoin/sign_tx/bitcoinlike.py',
            SOURCE_PY_DIR + 'apps/bitcoin/sign_tx/zcash_v4.py',
        ])
    )

    SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/evolu/*.py'))

    if BENCHMARK:
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/benchmark/*.py'))

    if THP:
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/thp/*.py'))

    if EVERYTHING:
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/common/definitions.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/common/definitions_constants.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/DefinitionType.py'))

        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/cardano/*.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/cardano/*/*.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/Cardano*.py'))

        if TREZOR_MODEL == "T2T1":
            SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/eos/*.py'))
            SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/eos/*/*.py'))
            SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/Eos*.py'))

        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/ethereum/*.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/Ethereum*.py'))

        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/monero/*.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/monero/*/*.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/monero/*/*/*.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/DebugMonero*.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/Monero*.py'))

        if TREZOR_MODEL == "T2T1":
            SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/nem/*.py'))
            SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/nem/*/*.py'))
            SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/NEM*.py'))

        if PYOPT == '0':
            SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/nostr/*.py'))
            SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/nostr/*/*.py'))
            SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/Nostr*.py'))
            SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/tron/*.py'))
            SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/Tron*.py'))

        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/ripple/*.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/Ripple*.py'))

        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/solana/*.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/solana/*/*.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/Solana*.py'))

        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/stellar/*.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/stellar/*/*.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/Stellar*.py'))

        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/tezos/*.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/Tezos*.py'))

        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/zcash/*.py'))

        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/webauthn/*.py'))

        if TREZOR_MODEL == "T2T1":
            SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/bitcoin/sign_tx/decred.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/bitcoin/sign_tx/bitcoinlike.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'apps/bitcoin/sign_tx/zcash_v4.py'))
        SOURCE_PY.extend(Glob(SOURCE_PY_DIR + 'trezor/enums/Zcash*.py'))

    source_mpy = env.FrozenModule(
        source=SOURCE_PY,
        source_dir=SOURCE_PY_DIR,
        bitcoin_only=BITCOIN_ONLY,
        backlight='backlight' in FEATURES_AVAILABLE,
        optiga='optiga' in FEATURES_AVAILABLE,
        use_ble='ble' in FEATURES_AVAILABLE,
        use_button='button' in FEATURES_AVAILABLE,
        use_touch='touch' in FEATURES_AVAILABLE,
        ui_layout=ui.get_ui_layout(TREZOR_MODEL),
        tropic='tropic' in FEATURES_AVAILABLE,
        thp=THP,
        power_manager='power_manager' in FEATURES_AVAILABLE,
        )

    source_mpyc = env.FrozenCFile(
        target='frozen_mpy.c', source=source_mpy, qstr_header=qstr_preprocessed)

    env.Depends(source_mpyc, qstr_generated)


#
# Program objects
#

source_files = SOURCE_MOD + SOURCE_MOD_CRYPTO + SOURCE_FIRMWARE + SOURCE_MICROPYTHON + SOURCE_MICROPYTHON_SPEED + SOURCE_HAL
obj_program = []
obj_program.extend(env.Object(source=SOURCE_MOD))
obj_program.extend(env.Object(source=SOURCE_MOD_CRYPTO, CCFLAGS='$CCFLAGS -ftrivial-auto-var-init=zero -ffreestanding'))
if FEATURE_FLAGS["SECP256K1_ZKP"]:
    obj_program.extend(env.Object(source=SOURCE_MOD_SECP256K1_ZKP, CCFLAGS='$CCFLAGS -Wno-unused-function -ffreestanding'))
    source_files.extend(SOURCE_MOD_SECP256K1_ZKP)
obj_program.extend(env.Object(source=SOURCE_FIRMWARE))
obj_program.extend(env.Object(source=SOURCE_MICROPYTHON))
obj_program.extend(env.Object(source=SOURCE_MICROPYTHON_SPEED, COPT='-O3'))
obj_program.extend(env.Object(source=SOURCE_HAL))
if FROZEN:
    obj_program.extend(env.Object(source=source_mpyc))

random.Random(SCM_REVISION).shuffle(obj_program)

env.Replace(
    ALLSOURCES=source_files,
    ALLDEFS=tools.get_defs_for_cmake(env['CPPDEFINES'] + env['CPPDEFINES_IMPLICIT'] + [f"PRODUCTION={int(PRODUCTION)}", f"BOOTLOADER_QA={int(BOOTLOADER_QA)}", f"PYOPT={PYOPT}", f"BITCOIN_ONLY={BITCOIN_ONLY}"]))


cmake_gen = env.Command(
    target='CMakeLists.txt',
    source='',
    action='$MAKECMAKELISTS --sources $ALLSOURCES --dirs $CPPPATH --defs $ALLDEFS',
)

#
# Rust library
#

protobuf_blobs = env.Command(
    target=[
        'rust/proto_enums.data',
        'rust/proto_msgs.data',
        'rust/proto_names.data',
        'rust/proto_wire.data',
    ],
    source=PROTO_SOURCES,
    action='$PB2PY --bitcoin-only=%s --blob-outdir ${TARGET.dir} $SOURCES --qstr-defs build/firmware/genhdr/qstrdefs.generated.h' % BITCOIN_ONLY,
)
env.Depends(protobuf_blobs, qstr_generated)


#
# Rust library
#
features = ['micropython', 'protobuf', 'ui', 'translations'] + FEATURES_AVAILABLE + RUST_UI_FEATURES
if PYOPT == '0':
    features.append('debug')
    features.append('ui_debug')
    features.append('ui_debug_overlay')
if EVERYTHING:
    features.append('universal_fw')
if UI_PERFORMANCE_OVERLAY:
    features.append('ui_performance_overlay')
if not PRODUCTION:
    features.append('dev_keys')


rust = tools.add_rust_lib(
    env=env,
    build='firmware',
    profile='release',
    features=features,
    all_paths=ALLPATHS,
    build_dir=str(Dir('.').abspath),
)
obj_program += [rust]


env.Depends(rust, protobuf_blobs)
env.Depends(rust, TRANSLATION_DATA)

BOOTLOADER_SUFFIX = TREZOR_MODEL
if BOOTLOADER_QA or BOOTLOADER_DEVEL:
    BOOTLOADER_SUFFIX += '_qa'

# select vendor header
if BOOTLOADER_QA or BOOTLOADER_DEVEL:
    if UNSAFE_FW:
        vendor = "unsafe_signed_dev"
    else:
        vendor = "dev_DO_NOT_SIGN_signed_dev"
elif not PRODUCTION:
    vendor = "unsafe_signed_prod"
else:
    if TREZOR_MODEL in ('T2T1',):
        vendor = "satoshilabs_signed_prod"
    elif BITCOIN_ONLY == '1':
        vendor = "trezor_btconly_signed_prod"
    else:
        vendor = "trezor_signed_prod"

VENDORHEADER = f'embed/models/{TREZOR_MODEL}/vendorheader/vendorheader_{vendor}.bin'

tools.embed_raw_binary(
        obj_program,
        env,
        'vendorheader',
        'embed/projects/firmware/vendorheader.o',
        VENDORHEADER,
        )

tools.embed_raw_binary(
        obj_program,
        env,
        'kernel',
        'build/kernel/kernel.o',
        f'build/kernel/kernel.bin',
        )

if 'nrf' in FEATURES_AVAILABLE:
    suffix = "-dev" if BOOTLOADER_DEVEL else ""

    tools.embed_raw_binary(
            obj_program,
            env,
            'nrf_app',
            'build/firmware/nrf_app.o',
            f'embed/models/{TREZOR_MODEL}/trezor-ble{suffix}.bin',
            )

if 'boot_ucb' in FEATURES_AVAILABLE:
    # embed uncompressed bootloader image
    tools.embed_raw_binary(
            obj_program,
            env,
            'bootloader',
            'embed/projects/bootloaders/bootloader.o',
            f'embed/models/{TREZOR_MODEL}/bootloaders/bootloader_{BOOTLOADER_SUFFIX}.bin',
        )
else:
    # embed compressed bootloader image
    tools.embed_compressed_binary(
            obj_program,
            env,
            'bootloader',
            'embed/projects/bootloaders/bootloader.o',
            f'embed/models/{TREZOR_MODEL}/bootloaders/bootloader_{BOOTLOADER_SUFFIX}.bin',
            'firmware',
            )

env.Depends(obj_program, qstr_generated)

linkerscript_gen = env.Command(
    target=env.get("ENV")["MEMORY_LAYOUT"],
    source=[f'embed/models/{TREZOR_MODEL}/{env.get("ENV")["MEMORY_LAYOUT"]}',  env.get('ENV')['LINKER_SCRIPT'].format(target='firmware')],
    action='$CAT $SOURCES > $TARGET',
)

program_elf = env.Command(
    target='firmware.elf',
    source=obj_program,
    action=
    '$LINK -o $TARGET $CCFLAGS $CFLAGS $SOURCES $LINKFLAGS -lc_nano -lm -lgcc',
)

env.Depends(program_elf, linkerscript_gen)

if CMAKELISTS != 0:
    env.Depends(program_elf, cmake_gen)

BINARY_NAME = f"build/firmware/firmware-{TREZOR_MODEL}"
if not EVERYTHING:
    BINARY_NAME += "-btconly"
BINARY_NAME += "-" + tools.get_version('embed/projects/firmware/version.h')
BINARY_NAME += "-" + tools.get_git_revision_short_hash()
BINARY_NAME += "-dirty" if tools.get_git_modified() else ""
BINARY_NAME += ".bin"


if 'STM32F427xx' in CPPDEFINES_HAL or 'STM32F429xx' in CPPDEFINES_HAL:
    action_bin=[
        '$OBJCOPY -O binary -j .vendorheader -j .header -j .flash -j .data --pad-to 0x08100000 $SOURCE ${TARGET}.p1',
        '$OBJCOPY -O binary -j .flash2 $SOURCE ${TARGET}.p2',
        '$CAT ${TARGET}.p1 ${TARGET}.p2 > $TARGET',
        '$HEADERTOOL -h $TARGET ' + ('-D' if not PRODUCTION else ''),
        '$DD if=$TARGET of=${TARGET}.p1 skip=0 bs=128k count=6',
        '$CP $TARGET ' + BINARY_NAME,
    ]
elif 'STM32U5G9xx' in CPPDEFINES_HAL or 'STM32U585xx' in CPPDEFINES_HAL:
    action_bin=[
        '$OBJCOPY -O binary -j .vendorheader -j .header -j .flash -j .data $SOURCE ${TARGET}',
        '$HEADERTOOL -h $TARGET ' + ('-D' if not PRODUCTION else ''),
        '$CP $TARGET ' + BINARY_NAME,
        ]
else:
    raise Exception("Unknown MCU")

if STORAGE_INSECURE_TESTING_MODE:
    INSECURE_TESTING_MODE_STR = """
#########################################################
#   STORAGE_INSECURE_TESTING_MODE enabled, DO NOT USE   #
#########################################################
"""
    action_bin.append(INSECURE_TESTING_MODE_STR)

program_bin = env.Command(
    target='firmware.bin',
    source=program_elf,
    action=action_bin,
)
