project('poly1', 'cpp', default_options: ['optimization=2', 'cpp_std=c++17'])

atpack_zip = 'Microchip.AVR-Dx_DFP.2.1.152.atpack'
dependencies = []

local_headers = ['.', 'etl/include']

sources = [
  'main.cpp',
  'board.cpp',
]

_includes = local_headers
_incl_dirs = include_directories(_includes)

# test binaries
if host_machine.cpu_family() != 'avr'
  test_midi = executable(
    'test_midi',
    ['test_midi.cpp'],
    include_directories: _incl_dirs,
  )
  subdir_done()
endif

# debug build
if get_option('buildtype') == 'debug'
    add_project_arguments(['-DDEBUG=1', '-ggdb3'], language: ['c', 'cpp'])
else
    add_project_arguments(['-ggdb3'], language: ['c', 'cpp'])
endif

objcopy = find_program('objcopy')
avrdude = find_program('avrdude', required: false, disabler: true)

atpack_path = meson.build_root() / 'atpack'
sysroot = atpack_path / 'gcc/dev' / host_machine.cpu()
add_project_arguments(['-B', sysroot], language: ['c', 'cpp'])
add_project_link_arguments(['-B', sysroot], language: ['c', 'cpp'])

add_project_arguments(['-mmcu=' + host_machine.cpu()], language: ['c', 'cpp'])
add_project_link_arguments(['-mmcu=' + host_machine.cpu()], language: ['c', 'cpp'])

add_project_arguments(['-DF_CPU=' + get_option('cpu_freq').to_string()], language: ['c', 'cpp'])
add_project_arguments(['-I' + atpack_path / 'include'], language: ['c', 'cpp'])

atpack = custom_target(
  'atpack',
  command: [ 'unzip', '@INPUT@', '-d', '@OUTPUT@' ],
  input: atpack_zip,
  output: 'atpack',
)

main = executable(
    meson.project_name() + '.elf',
    sources,
    atpack,
    include_directories: _incl_dirs,
    dependencies: dependencies,
)

main_hex = custom_target(
    meson.project_name() + '.hex',
    command: [
        objcopy,
        '-O', 'ihex',
        '@INPUT@', '@OUTPUT@'
    ],
    input: main,
    output: meson.project_name() + '.hex',
    build_by_default: true
)

if avrdude.found()
    # creates an empty file named 'flash' to get around meson's inability
    # to have a target create no outputs.
    #
    # TODO i don't think this is necessary...
    flash = custom_target(
        'flash',
        build_always_stale: true,
        command: [
            avrdude, '-p', host_machine.cpu(),
            '-c', get_option('programmer'),
            '-U', 'flash:w:@INPUT@:i'
        ],
        input: main_hex,
        capture: true,
        output: 'flash'
    )
endif
