#
#  Copyright (c) 2016, The OpenThread Authors.
#  All rights reserved.
#
#  Redistribution and use in source and binary forms, with or without
#  modification, are permitted provided that the following conditions are met:
#  1. Redistributions of source code must retain the above copyright
#     notice, this list of conditions and the following disclaimer.
#  2. Redistributions in binary form must reproduce the above copyright
#     notice, this list of conditions and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#  3. Neither the name of the copyright holder nor the
#     names of its contributors may be used to endorse or promote products
#     derived from this software without specific prior written permission.
#
#  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#  ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
#  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
#  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
#  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#  POSSIBILITY OF SUCH DAMAGE.
#

.NOTPARALLEL:

AR                              = arm-none-eabi-ar
CCAS                            = $(CCPREFIX) arm-none-eabi-gcc
CPP                             = arm-none-eabi-cpp
CC                              = $(CCPREFIX) arm-none-eabi-gcc
CXX                             = $(CCPREFIX) arm-none-eabi-g++
LD                              = arm-none-eabi-ld
STRIP                           = arm-none-eabi-strip
NM                              = arm-none-eabi-nm
RANLIB                          = arm-none-eabi-ranlib
OBJCOPY                         = arm-none-eabi-objcopy

BuildJobs                      ?= 10
GCCVersion                      = $(shell expr `$(CC) -dumpversion | cut -f1 -d.`)

configure_OPTIONS                                 = \
    --enable-ftd                                    \
    --enable-mtd                                    \
    --enable-diag                                   \
    --enable-linker-map                             \
    --with-examples=nrf52840                        \
    $(NULL)

ifneq ($(DISABLE_BUILTIN_MBEDTLS), 1)
configure_OPTIONS              += MBEDTLS_CPPFLAGS="$(NRF52840_MBEDTLS_CPPFLAGS)"
endif

ifdef SRC_PATH
configure_OPTIONS              += --srcdir="$(SRC_PATH)"
endif

TopSourceDir                    := $(dir $(shell readlink $(firstword $(MAKEFILE_LIST))))..
AbsTopSourceDir                 := $(dir $(realpath $(firstword $(MAKEFILE_LIST))))..

NRF52840_MBEDTLS_CPPFLAGS  = -DMBEDTLS_CONFIG_FILE='\"mbedtls-config.h\"'
NRF52840_MBEDTLS_CPPFLAGS += -DMBEDTLS_USER_CONFIG_FILE='\"nrf52840-mbedtls-config.h\"'
NRF52840_MBEDTLS_CPPFLAGS += -I$(AbsTopSourceDir)/third_party/mbedtls
NRF52840_MBEDTLS_CPPFLAGS += -I$(AbsTopSourceDir)/third_party/mbedtls/repo/include
NRF52840_MBEDTLS_CPPFLAGS += -I$(AbsTopSourceDir)/third_party/mbedtls/repo/include/mbedtls
NRF52840_MBEDTLS_CPPFLAGS += -I$(AbsTopSourceDir)/third_party/NordicSemiconductor/libraries/crypto
NRF52840_MBEDTLS_CPPFLAGS += -I$(AbsTopSourceDir)/third_party/NordicSemiconductor/libraries/nrf_cc310/include
NRF52840_MBEDTLS_CPPFLAGS += -I$(AbsTopSourceDir)/third_party/NordicSemiconductor/nrfx/mdk
NRF52840_MBEDTLS_CPPFLAGS += -I$(AbsTopSourceDir)/third_party/NordicSemiconductor/cmsis
NRF52840_MBEDTLS_CPPFLAGS += -DNRF52840_XXAA

CONFIG_FILE      = OPENTHREAD_PROJECT_CORE_CONFIG_FILE='\"openthread-core-nrf52840-config.h\"'
CONFIG_FILE_PATH = $(AbsTopSourceDir)/examples/platforms/nrf52840/

COMMONCFLAGS                   := \
    -fdata-sections               \
    -ffunction-sections           \
    -Os                           \
    -g                            \
    -D$(CONFIG_FILE)              \
    -I$(CONFIG_FILE_PATH)         \
    $(NULL)

include $(dir $(abspath $(lastword $(MAKEFILE_LIST))))/common-switches.mk

ifneq ($(CERT_LOG),1)
COMMONCFLAGS += -DOPENTHREAD_CONFIG_LOG_OUTPUT=OPENTHREAD_CONFIG_LOG_OUTPUT_PLATFORM_DEFINED
endif

ifeq ($(BOOTLOADER),1)
configure_OPTIONS += --with-custom-linker-file=$(AbsTopSourceDir)/examples/platforms/nrf52840/nrf52840_bootloader.ld
COMMONCFLAGS += -DAPP_USBD_NRF_DFU_TRIGGER_ENABLED=1
endif

#
# Select transport which CLI, NCP and RCP examples will use to communicate.
# To disable all transports use the DISABLE_TRANSPORTS switch. This will disable
# the build of all above examples.
# If NCP_SPI switch is set, only NCP and RCP examples will be built.
# Otherwise the user can select USB transport. If no transports were selected,
# the default serial transport is UART.
#
ifndef DISABLE_TRANSPORTS
configure_OPTIONS              += --enable-ncp
configure_OPTIONS              += --enable-radio-only
ifeq ($(NCP_SPI),1)
COMMONCFLAGS                   += -DSPIS_AS_SERIAL_TRANSPORT=1
configure_OPTIONS              += --with-ncp-bus=spi
else
configure_OPTIONS              += --with-ncp-bus=uart
configure_OPTIONS              += --enable-cli
ifeq ($(USB),1)
COMMONCFLAGS                   += -DUSB_CDC_AS_SERIAL_TRANSPORT=1
else
COMMONCFLAGS                   += -DUART_AS_SERIAL_TRANSPORT=1
endif # USB     == 1
endif # NCP_SPI == 1
endif # DISABLE_TRANSPORTS

ifeq ($(DISABLE_CC310), 1)
NRF52840_MBEDTLS_CPPFLAGS += -DDISABLE_CC310=1
endif

ifeq ($(MBEDTLS_THREADING), 1)
NRF52840_MBEDTLS_CPPFLAGS += -DDISABLE_CC310=1
NRF52840_MBEDTLS_CPPFLAGS += -DMBEDTLS_THREADING=1
endif

ifdef MBEDTLS_THREADING_MUTEX_DEF
NRF52840_MBEDTLS_CPPFLAGS += -DMBEDTLS_THREADING_MUTEX_DEF='\"$(MBEDTLS_THREADING_MUTEX_DEF)\"'
endif

ifeq ($(shell expr $(GCCVersion) \>= 7), 1)
    COMMONCFLAGS += -Wno-expansion-to-defined
endif

CPPFLAGS                       += \
    $(COMMONCFLAGS)               \
    $(target_CPPFLAGS)            \
    $(NULL)

CFLAGS                         += \
    $(COMMONCFLAGS)               \
    $(target_CFLAGS)              \
    $(NULL)

CXXFLAGS                       += \
    $(COMMONCFLAGS)               \
    $(target_CXXFLAGS)            \
    -fno-exceptions               \
    -fno-rtti                     \
    $(NULL)

LDFLAGS                        += \
    $(COMMONCFLAGS)               \
    $(target_LDFLAGS)             \
    -specs=nano.specs             \
    -specs=nosys.specs            \
    -Wl,--gc-sections             \
    $(NULL)

CCASFLAGS                       += \
    $(COMMONCCASFLAGS)             \
    $(target_CCASFLAGS)            \
    -x                             \
    assembler-with-cpp             \
    $(NULL)

ECHO                            := @echo
MAKE                            := make
MKDIR_P                         := mkdir -p
LN_S                            := ln -s
RM_F                            := rm -f

INSTALL                         := /usr/bin/install
INSTALLFLAGS                    := -p

BuildPath                       = build
TopBuildDir                     = $(BuildPath)
AbsTopBuildDir                  = $(PWD)/$(TopBuildDir)

ResultPath                      = output
TopResultDir                    = $(ResultPath)
AbsTopResultDir                 = $(PWD)/$(TopResultDir)

TargetTuple                     = nrf52840

ARCHS                           = cortex-m4

TopTargetLibDir                 = $(TopResultDir)/$(TargetTuple)/lib

ifndef BuildJobs
BuildJobs := $(shell getconf _NPROCESSORS_ONLN)
endif
JOBSFLAG := -j$(BuildJobs)

#
# configure-arch <arch>
#
# Configure OpenThread for the specified architecture.
#
#   arch - The architecture to configure.
#
define configure-arch
$(ECHO) "  CONFIG   $(TargetTuple)..."
(cd $(BuildPath)/$(TargetTuple) && $(AbsTopSourceDir)/configure \
INSTALL="$(INSTALL) $(INSTALLFLAGS)" \
CPP="$(CPP)" CC="$(CC)" CXX="$(CXX)" CCAS="$(CCAS)" OBJC="$(OBJC)" OBJCXX="$(OBJCXX)" AR="$(AR)" RANLIB="$(RANLIB)" NM="$(NM)" STRIP="$(STRIP)" CPPFLAGS="$(CPPFLAGS)" CFLAGS="$(CFLAGS)" CXXFLAGS="$(CXXFLAGS)" CCASFLAGS="$(CCASFLAGS)" LDFLAGS="$(LDFLAGS)" \
--host=arm-none-eabi \
--prefix=/ \
--exec-prefix=/$(TargetTuple) \
$(configure_OPTIONS))
endef # configure-arch

#
# build-arch <arch>
#
# Build the OpenThread intermediate build products for the specified
# architecture.
#
#   arch - The architecture to build.
#
define build-arch
$(ECHO) "  BUILD    $(TargetTuple)"
$(MAKE) $(JOBSFLAG) -C $(BuildPath)/$(TargetTuple) --no-print-directory \
all
endef # build-arch

#
# stage-arch <arch>
#
# Stage (install) the OpenThread final build products for the specified
# architecture.
#
#   arch - The architecture to stage.
#
define stage-arch
$(ECHO) "  STAGE    $(TargetTuple)"
$(MAKE) $(JOBSFLAG) -C $(BuildPath)/$(TargetTuple) --no-print-directory \
DESTDIR=$(AbsTopResultDir) \
install
endef # stage-arch

#
# ARCH_template <arch>
#
# Define macros, targets and rules to configure, build, and stage the
# OpenThread for a single architecture.
#
#   arch - The architecture to instantiate the template for.
#
define ARCH_template
CONFIGURE_TARGETS += configure-$(1)
BUILD_TARGETS     += do-build-$(1)
STAGE_TARGETS     += stage-$(1)
BUILD_DIRS        += $(BuildPath)/$(TargetTuple)
DIRECTORIES       += $(BuildPath)/$(TargetTuple)

configure-$(1): target_CPPFLAGS=$($(1)_target_CPPFLAGS)
configure-$(1): target_CFLAGS=$($(1)_target_CFLAGS)
configure-$(1): target_CXXFLAGS=$($(1)_target_CXXFLAGS)
configure-$(1): target_LDFLAGS=$($(1)_target_LDFLAGS)
configure-$(1): target_CCASFLAGS=$($(1)_target_CCASFLAGS)

configure-$(1): $(BuildPath)/$(TargetTuple)/config.status

$(BuildPath)/$(TargetTuple)/config.status: | $(BuildPath)/$(TargetTuple)
	$$(call configure-arch,$(1))

do-build-$(1): configure-$(1)

do-build-$(1):
	+$$(call build-arch,$(1))

stage-$(1): do-build-$(1)

stage-$(1): | $(TopResultDir)
	$$(call stage-arch,$(1))

$(1): stage-$(1)
endef # ARCH_template

.DEFAULT_GOAL := all

all: stage

#
# Cortex-m4
#

cortex-m4_target_ABI                  = cortex-m4
cortex-m4_target_CPPFLAGS             = -mcpu=cortex-m4 -mfloat-abi=hard -mfpu=fpv4-sp-d16 -mthumb -mabi=aapcs
cortex-m4_target_CFLAGS               = -mcpu=cortex-m4 -mfloat-abi=hard -mfpu=fpv4-sp-d16 -mthumb -mabi=aapcs
cortex-m4_target_CXXFLAGS             = -mcpu=cortex-m4 -mfloat-abi=hard -mfpu=fpv4-sp-d16 -mthumb -mabi=aapcs
cortex-m4_target_LDFLAGS              = -mcpu=cortex-m4 -mfloat-abi=hard -mfpu=fpv4-sp-d16 -mthumb -mabi=aapcs

# Instantiate an architecture-specific build template for each target
# architecture.

$(foreach arch,$(ARCHS),$(eval $(call ARCH_template,$(arch))))

#
# Flashing / Debugging
#

TARGET_APP ?= ot-cli-ftd
APP_FILE_NAME = $(TopResultDir)/$(TargetTuple)/bin/$(TARGET_APP)
APP_FILE_HEX = $(TopResultDir)/$(TargetTuple)/bin/$(TARGET_APP).hex

nrfjprog: $(APP_FILE_NAME)
	arm-none-eabi-objcopy -O ihex $(<) $(APP_FILE_HEX)
	nrfjprog -f NRF52 --sectorerase  --reset --program $(APP_FILE_HEX)

#
# Common / Finalization
#

configure: $(CONFIGURE_TARGETS)

build: $(BUILD_TARGETS)

stage: $(STAGE_TARGETS)

DIRECTORIES     = $(TopResultDir) $(TopResultDir)/$(TargetTuple)/lib $(BUILD_DIRS)

CLEAN_DIRS      = $(TopResultDir) $(BUILD_DIRS)

all: stage

$(DIRECTORIES):
	$(ECHO) "  MKDIR    $@"
	@$(MKDIR_P) "$@"

clean:
	$(ECHO) "  CLEAN"
	@$(RM_F) -r $(CLEAN_DIRS)

help:
	$(ECHO) "Simply type 'make -f $(firstword $(MAKEFILE_LIST))' to build OpenThread for the following "
	$(ECHO) "architectures: "
	$(ECHO) ""
	$(ECHO) "    $(ARCHS)"
	$(ECHO) ""
	$(ECHO) "To build only a particular architecture, specify: "
	$(ECHO) ""
	$(ECHO) "    make -f $(firstword $(MAKEFILE_LIST)) <architecture>"
	$(ECHO) ""
