# pylint: disable=E0602

import os

CCFLAGS_MOD = ''
CPPPATH_MOD = []
CPPDEFINES_MOD = []
SOURCE_MOD = []

PYOPT = '1'

# modtrezorconfig
SOURCE_MOD += [
    'embed/extmod/modtrezorconfig/modtrezorconfig.c',
    'embed/extmod/modtrezorconfig/norcow.c',
    'embed/extmod/modtrezorconfig/storage.c',
]

# modtrezorcrypto
CCFLAGS_MOD += '-Wno-sequence-point '
CPPPATH_MOD += [
    'vendor/trezor-crypto',
]
CPPDEFINES_MOD += [
    'AES_128',
    'AES_192',
    'RAND_PLATFORM_INDEPENDENT',
    ('USE_KECCAK', '1'),
    ('USE_ETHEREUM', '1'),
]
SOURCE_MOD += [
    'embed/extmod/modtrezorcrypto/modtrezorcrypto.c',
    'embed/extmod/modtrezorcrypto/crc.c',
    'embed/extmod/modtrezorcrypto/rand.c',
    'vendor/trezor-crypto/address.c',
    'vendor/trezor-crypto/aes/aescrypt.c',
    'vendor/trezor-crypto/aes/aeskey.c',
    'vendor/trezor-crypto/aes/aes_modes.c',
    'vendor/trezor-crypto/aes/aestab.c',
    'vendor/trezor-crypto/base58.c',
    'vendor/trezor-crypto/bignum.c',
    'vendor/trezor-crypto/bip32.c',
    'vendor/trezor-crypto/bip39.c',
    'vendor/trezor-crypto/blake256.c',
    'vendor/trezor-crypto/blake2b.c',
    'vendor/trezor-crypto/blake2s.c',
    'vendor/trezor-crypto/curves.c',
    'vendor/trezor-crypto/ecdsa.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/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.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/modm-donna-32bit.c',
    'vendor/trezor-crypto/hasher.c',
    'vendor/trezor-crypto/hmac.c',
    'vendor/trezor-crypto/memzero.c',
    'vendor/trezor-crypto/nist256p1.c',
    'vendor/trezor-crypto/pbkdf2.c',
    'vendor/trezor-crypto/rand.c',
    'vendor/trezor-crypto/ripemd160.c',
    'vendor/trezor-crypto/secp256k1.c',
    'vendor/trezor-crypto/sha2.c',
    'vendor/trezor-crypto/sha3.c',
]

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

# modtrezorui
CPPDEFINES_MOD += [
    'TREZOR_FONT_BOLD_ENABLE',
    'TREZOR_FONT_MONO_ENABLE',
    'TREZOR_FONT_NORMAL_ENABLE',
    ('QR_MAX_VERSION', '0'),
]
SOURCE_MOD += [
    'embed/extmod/modtrezorui/display.c',
    'embed/extmod/modtrezorui/inflate.c',
    'embed/extmod/modtrezorui/font_bitmap.c',
    'embed/extmod/modtrezorui/font_roboto_bold_20.c',
    'embed/extmod/modtrezorui/font_roboto_regular_20.c',
    'embed/extmod/modtrezorui/font_robotomono_regular_20.c',
    'embed/extmod/modtrezorui/modtrezorui.c',
    'embed/extmod/modtrezorui/trezor-qrenc/qr_encode.c',
]

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

# modutime
SOURCE_MOD += [
    'embed/firmware/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/lib/embed/abort_.c',
    'vendor/micropython/lib/mp-readline/readline.c',
    'vendor/micropython/lib/utils/interrupt_char.c',
    'vendor/micropython/lib/utils/printf.c',
    'vendor/micropython/lib/utils/pyexec.c',
    'vendor/micropython/lib/utils/stdout_helpers.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_longlong.c',
    'vendor/micropython/py/objint_mpz.c',
    'vendor/micropython/py/objint.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/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_utils.c',
    'vendor/micropython/py/runtime.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',
    'vendor/micropython/ports/stm32/gccollect.c',
    'vendor/micropython/ports/stm32/gchelper.s',
    'vendor/micropython/ports/stm32/pendsv.c',
]

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

SOURCE_STMHAL = [
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_adc_ex.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_adc.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_can.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_cortex.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dac_ex.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dac.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_dma.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_flash_ex.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_flash.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_gpio.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_i2c.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pcd_ex.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pcd.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pwr_ex.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_pwr.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rcc_ex.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rcc.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rng.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rtc_ex.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_rtc.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sd.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_spi.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_sram.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_tim_ex.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_tim.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal_uart.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_hal.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_fmc.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_sdmmc.c',
    'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Src/stm32f4xx_ll_usb.c',
]

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

SOURCE_TREZORHAL = [
    'embed/trezorhal/common.c',
    'embed/trezorhal/flash.c',
    'embed/trezorhal/mini_printf.c',
    'embed/trezorhal/mpu.c',
    'embed/trezorhal/rng.c',
    'embed/trezorhal/sbu.c',
    'embed/trezorhal/sdcard.c',
    'embed/trezorhal/stm32.c',
    'embed/trezorhal/systick.c',
    'embed/trezorhal/touch.c',
    'embed/trezorhal/usb.c',
    'embed/trezorhal/usbd_conf.c',
    'embed/trezorhal/usbd_core.c',
    'embed/trezorhal/usbd_ctlreq.c',
    'embed/trezorhal/usbd_ioreq.c',
    'embed/trezorhal/util.s',
    'embed/trezorhal/vectortable.s',
]

SOURCE_QSTR = SOURCE_MOD + SOURCE_MICROPYTHON + SOURCE_MICROPYTHON_SPEED

# TODO: recursive Glob
SOURCE_PY = Glob('src/*.py')
SOURCE_PY.extend(Glob('src/*/*.py'))
SOURCE_PY.extend(Glob('src/*/*/*.py'))
SOURCE_PY.extend(Glob('src/*/*/*/*.py'))
SOURCE_PY.extend(Glob('src/*/*/*/*/*.py'))
SOURCE_PY_DIR = 'src/'

env = Environment(ENV=os.environ, CFLAGS='%s -DPRODUCTION=%s -DPYOPT=%s' % (ARGUMENTS.get('CFLAGS', ''), ARGUMENTS.get('PRODUCTION', '0'), PYOPT))

env.Tool('micropython')

env.Replace(
    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(
    COPT='-Os',
    CCFLAGS='$COPT '
    '-g3 '
    '-nostdlib '
    '-std=gnu99 -Wall -Werror -Wdouble-promotion -Wpointer-arith -fno-common '
    '-mthumb -mtune=cortex-m4 -mcpu=cortex-m4 -mfpu=fpv4-sp-d16 -mfloat-abi=hard '
    '-fsingle-precision-constant -fdata-sections -ffunction-sections '
    '-ffreestanding '
    '-fstack-protector-all '
    + CCFLAGS_MOD,
    CCFLAGS_QSTR='-DNO_QSTR -DN_X64 -DN_X86 -DN_THUMB',
    LINKFLAGS='-T embed/firmware/memory.ld -Wl,--gc-sections -Wl,-Map=build/firmware/firmware.map -Wl,--warn-common',
    CPPPATH=[
        '.',
        'embed/firmware',
        'embed/trezorhal',
        'embed/extmod/modtrezorui',
        'vendor/micropython',
        'vendor/micropython/lib/stm32lib/STM32F4xx_HAL_Driver/Inc',
        'vendor/micropython/lib/stm32lib/CMSIS/STM32F4xx/Include',
        'vendor/micropython/lib/cmsis/inc',
        'vendor/micropython/ports/stm32',
    ] + CPPPATH_MOD,
    CPPDEFINES=[
        'TREZOR_MODEL_T',
        'MCU_SERIES_F4',
        'STM32F427xx',
        'USE_HAL_DRIVER',
        ('STM32_HAL_H', '"<stm32f4xx.h>"'),
    ] + CPPDEFINES_MOD,
    ASFLAGS='-mthumb -mcpu=cortex-m4 -mfloat-abi=hard -mfpu=fpv4-sp-d16',
    ASPPFLAGS='$CFLAGS $CCFLAGS', )

env.Replace(
    BINCTL='tools/binctl',
    KEYCTL='tools/keyctl',
    PYTHON='python',
    MAKEQSTRDATA='$PYTHON vendor/micropython/py/makeqstrdata.py',
    MAKEVERSIONHDR='$PYTHON vendor/micropython/py/makeversionhdr.py',
    MPY_TOOL='$PYTHON vendor/micropython/tools/mpy-tool.py',
    MPY_CROSS='vendor/micropython/mpy-cross/mpy-cross -O' + PYOPT
)

#
# Micropython version
#

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

#
# Qstrings
#

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

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

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

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

env.Ignore(qstr_collected, qstr_generated)

#
# Frozen modules
#

source_mpy = env.FrozenModule(source=SOURCE_PY, source_dir=SOURCE_PY_DIR)

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

env.Depends(source_mpyc, qstr_generated)

#
# Program objects
#

obj_program = []
obj_program.extend(env.Object(source=SOURCE_MOD))
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_STMHAL))
obj_program.extend(env.Object(source=SOURCE_TREZORHAL))
obj_program.extend(env.Object(source=source_mpyc))

VENDORHEADER = 'embed/vendorheader/vendorheader_' + ('unsafe_signed_prod.bin' if ARGUMENTS.get('PRODUCTION', '0') == '0' else 'satoshilabs_signed_prod.bin')

obj_program.extend(
    env.Command(
        target='embed/firmware/vendorheader.o',
        source=VENDORHEADER,
        action='$OBJCOPY -I binary -O elf32-littlearm -B arm'
        ' --rename-section .data=.vendorheader,alloc,load,readonly,contents'
        ' $SOURCE $TARGET', ))

env.Depends(obj_program, qstr_generated)

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

program_bin = env.Command(
    target='firmware.bin',
    source=program_elf,
    action=[
        '$OBJCOPY -O binary -j .vendorheader -j .header -j .flash -j .data $SOURCE $TARGET',
        '$BINCTL $TARGET -h',
        '$BINCTL $TARGET -s 1:2 `$KEYCTL sign firmware $TARGET 4747474747474747474747474747474747474747474747474747474747474747 4848484848484848484848484848484848484848484848484848484848484848`' if ARGUMENTS.get('PRODUCTION', '0') == '0' else '',
    ], )
