# pylint: disable=E0602

import os
import tools

TREZOR_MODEL = ARGUMENTS.get('TREZOR_MODEL', 'T')
CMAKELISTS = int(ARGUMENTS.get('CMAKELISTS', 0))
BOOTLOADER_QA = ARGUMENTS.get('BOOTLOADER_QA', '0') == '1'
PRODUCTION = 0 if BOOTLOADER_QA else ARGUMENTS.get('PRODUCTION', '0') == '1'

if TREZOR_MODEL in ('1', ):
    # skip bootloader build
    env = Environment()
    def build_bootloader(target,source,env):
        print(f'Bootloader: nothing to build for Model {TREZOR_MODEL}')
    program_bin = env.Command(
                 target='bootloader.bin',
                 source=None,
                 action=build_bootloader
             )
    Return()

FEATURES_WANTED = ["input", "rgb_led", "consumption_mask", "usb", "optiga"]

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

if TREZOR_MODEL in ('R', ):
    FONT_NORMAL='Font_PixelOperator_Regular_8'
    FONT_DEMIBOLD='Font_PixelOperator_Regular_8'
    FONT_BOLD='Font_PixelOperator_Bold_8'
    FONT_MONO='Font_PixelOperator_Regular_8'
    FONT_BIG=None
elif TREZOR_MODEL in ('T', 'DISC1'):
    FONT_NORMAL='Font_TTHoves_Regular_21'
    FONT_DEMIBOLD=None
    FONT_BOLD='Font_TTHoves_Bold_17'
    FONT_MONO=None
    FONT_BIG=None

# modtrezorcrypto
CCFLAGS_MOD += '-Wno-sequence-point '
CPPPATH_MOD += [
    'vendor/trezor-crypto',
    'vendor/trezor-storage',
]
CPPDEFINES_MOD += [
    'AES_128',
    'AES_192',
    'USE_KECCAK',
    'ED25519_NO_PRECOMP',
    'TREZOR_UI2',
    'FANCY_FATAL_ERROR',
]

SOURCE_MOD += [
    'vendor/trezor-crypto/blake2s.c',
    'vendor/trezor-crypto/chacha_drbg.c',
    'vendor/trezor-crypto/chacha20poly1305/chacha_merged.c',
    'vendor/trezor-crypto/ed25519-donna/curve25519-donna-32bit.c',
    'vendor/trezor-crypto/ed25519-donna/curve25519-donna-helpers.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-impl-base.c',
    'vendor/trezor-crypto/ed25519-donna/modm-donna-32bit.c',
    'vendor/trezor-crypto/memzero.c',
    'vendor/trezor-crypto/rand.c',
    'vendor/trezor-crypto/sha2.c',
]

# modtrezorui
CPPPATH_MOD += [
        'vendor/micropython/lib/uzlib',
]

SOURCE_MOD += [
    'embed/extmod/modtrezorcrypto/rand.c',
    'embed/lib/buffers.c',
    'embed/lib/colors.c',
    'embed/lib/display_utils.c',
    'embed/lib/display.c',
    'embed/lib/fonts/font_bitmap.c',
    'embed/lib/fonts/fonts.c',
    'embed/lib/image.c',
    'embed/lib/mini_printf.c',
    'embed/lib/terminal.c',
    'embed/lib/unit_variant.c',
    'vendor/micropython/lib/uzlib/adler32.c',
    'vendor/micropython/lib/uzlib/crc32.c',
    'vendor/micropython/lib/uzlib/tinflate.c',
    'vendor/trezor-storage/flash_common.c',
]

SOURCE_NANOPB = [
    'vendor/nanopb/pb_common.c',
    'vendor/nanopb/pb_decode.c',
    'vendor/nanopb/pb_encode.c',
]

SOURCE_BOOTLOADER = [
    'embed/bootloader/startup.s',
    'embed/bootloader/header.S',
    'embed/bootloader/bootui.c',
    'embed/bootloader/main.c',
    'embed/bootloader/messages.c',
    'embed/bootloader/protob/messages.pb.c',
]

# fonts
tools.add_font('NORMAL', FONT_NORMAL, CPPDEFINES_MOD, SOURCE_MOD)
tools.add_font('BOLD', FONT_BOLD, CPPDEFINES_MOD, SOURCE_MOD)
tools.add_font('DEMIBOLD', FONT_DEMIBOLD, CPPDEFINES_MOD, SOURCE_MOD)
tools.add_font('MONO', FONT_MONO, CPPDEFINES_MOD, SOURCE_MOD)
tools.add_font('BIG', FONT_BIG, CPPDEFINES_MOD, SOURCE_MOD)

env = Environment(ENV=os.environ, CFLAGS=f"{ARGUMENTS.get('CFLAGS', '')} -DPRODUCTION={int(PRODUCTION)} -DBOOTLOADER_QA={int(BOOTLOADER_QA)}")

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

env.Replace(
    CP='cp',
    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',
    PYTHON='python',
    MAKECMAKELISTS='$PYTHON tools/make_cmakelists.py', )

env.Replace(
    TREZOR_MODEL=TREZOR_MODEL, )

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 '
    '-ffreestanding '
    '-fstack-protector-all '
    +  env.get('ENV')["CPU_CCFLAGS"] + CCFLAGS_MOD,
    CCFLAGS_QSTR='-DNO_QSTR -DN_X64 -DN_X86 -DN_THUMB',
    LINKFLAGS='-T embed/bootloader/memory.ld -Wl,--gc-sections -Wl,-Map=build/bootloader/bootloader.map -Wl,--warn-common -Wl,--print-memory-usage',
    CPPPATH=[
        'embed/rust',
        'embed/bootloader',
        'embed/bootloader/nanopb',
        'embed/bootloader/protob',
        'embed/lib',
        'embed/models',
        'embed/trezorhal',
        'embed/extmod/modtrezorui',
        'vendor/micropython/lib/cmsis/inc',
        'vendor/nanopb',
    ] + CPPPATH_MOD + PATH_HAL,
    CPPDEFINES=[
        'BOOTLOADER',
        'TREZOR_MODEL_'+TREZOR_MODEL,
        'USE_HAL_DRIVER',
        'PB_FIELD_16BIT',
        'PB_ENCODE_ARRAYS_UNPACKED',
        'PB_VALIDATE_UTF8',
    ] + CPPDEFINES_MOD + CPPDEFINES_HAL,
    ASFLAGS=env.get('ENV')['CPU_ASFLAGS'],
    ASPPFLAGS='$CFLAGS $CCFLAGS',
    )

env.Replace(
    HEADERTOOL='tools/headertool.py',
)

env.Replace(
    ALLSOURCES=SOURCE_MOD + SOURCE_BOOTLOADER + SOURCE_NANOPB + SOURCE_HAL,
    ALLDEFS=tools.get_defs_for_cmake(env['CPPDEFINES'] + [f"PRODUCTION={int(PRODUCTION)}", f"BOOTLOADER_QA={int(BOOTLOADER_QA)}"]))

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


#
# Rust library
#

RUST_PROFILE = 'release'
RUST_LIB = 'trezor_lib'
RUST_LIBDIR = f'build/bootloader/rust/{env.get("ENV")["RUST_TARGET"]}/{RUST_PROFILE}'
RUST_LIBPATH = f'{RUST_LIBDIR}/lib{RUST_LIB}.a'

def cargo_build():
    # Determine the profile build flags.
    if RUST_PROFILE == 'release':
        profile = '--release'
    else:
        profile = ''
    if TREZOR_MODEL in ("1",):
        features = ["model_t1"]
    elif TREZOR_MODEL in ("R",):
        features = ["model_tr"]
    else:
        features = ["model_tt"]
    features.append("bitcoin_only")
    features.append("ui")
    features.append("bootloader")
    features.extend(FEATURES_AVAILABLE)

    cargo_opts = [
        f'--target={env.get("ENV")["RUST_TARGET"]}',
        f'--target-dir=../../build/bootloader/rust',
        '--no-default-features',
        '--features ' + ','.join(features),
        '-Z build-std=core',
        '-Z build-std-features=panic_immediate_abort',
    ]

    return f'cd embed/rust; cargo build {profile} ' + ' '.join(cargo_opts)

rust = env.Command(
    target=RUST_LIBPATH,
    source='',
    action=cargo_build(), )

env.Append(LINKFLAGS=f' -L{RUST_LIBDIR}')
env.Append(LINKFLAGS=f' -l{RUST_LIB}')

#
# Program objects
#

obj_program = []
obj_program += env.Object(source=SOURCE_MOD)
obj_program += env.Object(source=SOURCE_BOOTLOADER)
obj_program += env.Object(source=SOURCE_NANOPB)
obj_program += env.Object(source=SOURCE_HAL)


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

env.Depends(program_elf, rust)

SUFFIX = '_qa' if BOOTLOADER_QA else ''

BINARY_NAME = f"build/bootloader/bootloader-{tools.get_model_identifier(TREZOR_MODEL)}{SUFFIX}"
BINARY_NAME += "-" + tools.get_version('embed/bootloader/version.h')
BINARY_NAME += "-" + tools.get_git_revision_short_hash()
BINARY_NAME += "-dirty" if tools.get_git_modified() else ""
BINARY_NAME += ".bin"

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

program_bin = env.Command(
    target='bootloader.bin',
    source=program_elf,
    action=[
        '$OBJCOPY -O binary -j .header -j .flash -j .data $SOURCE $TARGET',
        '$HEADERTOOL $TARGET ' + ('-D' if not PRODUCTION else ''),
        '$CP $TARGET ' + BINARY_NAME,
    ], )