CPU = cortex-m4
CROSS_COMPILE ?= arm-none-eabi-

NRF_PATH := nrf5sdk/

INCLUDES += src/platform/nrf52/sdk
INCLUDES += src/platform/cm4/cmsis/include

NRF_C_SRCS += src/platform/nrf52/sdk/system_nrf52.c
C_OBJS += $(patsubst $(SRC_DIR)%,$(OBJ_DIR)%,$(patsubst %.c,%.c.o,$(NRF_C_SRCS)))

NRF_A_SRCS = src/platform/nrf52/sdk/gcc_startup_nrf52.S
A_OBJS += $(patsubst $(SRC_DIR)%,$(OBJ_DIR)/%,$(patsubst %.S,%.o,$(NRF_A_SRCS)))

C_FLAGS += -DBOARD_PCA10040
C_FLAGS += -DBSP_DEFINES_ONLY
C_FLAGS += -DCONFIG_GPIO_AS_PINRESET
C_FLAGS += -DFLOAT_ABI_HARD
C_FLAGS += -DNRF52
C_FLAGS += -DNRF52832_XXAA
C_FLAGS += -DNRF52_PAN_74
# C_FLAGS += -DNRF_SD_BLE_API_VERSION=7
# C_FLAGS += -DS132
# C_FLAGS += -DSOFTDEVICE_PRESENT
C_FLAGS += -mcpu=$(CPU)
C_FLAGS += -mthumb -mabi=aapcs
C_FLAGS += -mfloat-abi=hard -mfpu=fpv4-sp-d16
C_FLAGS += -fno-builtin -fshort-enums
C_FLAGS += -D__HEAP_SIZE=8192
C_FLAGS += -D__HEAP_SIZE=8192

CXX_FLAGS += -DBOARD_PCA10040
CXX_FLAGS += -DBSP_DEFINES_ONLY
CXX_FLAGS += -DCONFIG_GPIO_AS_PINRESET
CXX_FLAGS += -DFLOAT_ABI_HARD
CXX_FLAGS += -DNRF52
CXX_FLAGS += -DNRF52832_XXAA
CXX_FLAGS += -DNRF52_PAN_74
# CXX_FLAGS += -DNRF_SD_BLE_API_VERSION=7
# CXX_FLAGS += -DS132
# CXX_FLAGS += -DSOFTDEVICE_PRESENT
CXX_FLAGS += -mcpu=$(CPU)
CXX_FLAGS += -mthumb -mabi=aapcs
CXX_FLAGS += -mfloat-abi=hard -mfpu=fpv4-sp-d16
CXX_FLAGS += -fno-builtin -fshort-enums
CXX_FLAGS += -D__HEAP_SIZE=8192
CXX_FLAGS += -D__HEAP_SIZE=8192

# Assembler flags common to all targets
A_FLAGS += -g$(OPT)
A_FLAGS += -mcpu=$(CPU)
A_FLAGS += -mthumb -mabi=aapcs
A_FLAGS += -mfloat-abi=hard -mfpu=fpv4-sp-d16
A_FLAGS += -DBOARD_PCA10040
A_FLAGS += -DBSP_DEFINES_ONLY
A_FLAGS += -DCONFIG_GPIO_AS_PINRESET
A_FLAGS += -DFLOAT_ABI_HARD
A_FLAGS += -DNRF52
A_FLAGS += -DNRF52832_XXAA
A_FLAGS += -DNRF52_PAN_74
# A_FLAGS += -DNRF_SD_BLE_API_VERSION=7
# A_FLAGS += -DS132
# A_FLAGS += -DSOFTDEVICE_PRESENT
A_FLAGS += -D__HEAP_SIZE=8192
A_FLAGS += -D__HEAP_SIZE=8192

LINKER_SCRIPT = without_sd.ld

# Linker flags
LD_FLAGS += -O$(OPT) -g$(OPT)
LD_FLAGS += -mthumb -mabi=aapcs -Lbuild_system/platform/$(PLATFORM) -T$(LINKER_SCRIPT)
LD_FLAGS += -mcpu=$(CPU)
LD_FLAGS += -mfloat-abi=hard -mfpu=fpv4-sp-d16
LD_FLAGS += -Wl,--gc-sections
LD_FLAGS += --specs=nano.specs

LIBS += c nosys m

.PHONY: package flash flash_softdevice erase

package: $(TARGET_HEX)
	nrfutil pkg generate --hw-version 52 --application-version 1 --application $(TARGET_HEX) --sd-req 0xCB --sd-id 0xCB --key-file keys/private.key $(TARGET_PACKAGE)

flash: $(TARGET_HEX)
	@echo Flashing: $(TARGET_HEX)
	nrfjprog -f nrf52 --program $(TARGET_HEX) --sectorerase
	nrfjprog -f nrf52 --reset

flash_softdevice: $(THIS_MAKEFILE)
	@echo Flashing: $(NRF_PATH)/components/softdevice/s132/hex/s132_nrf52_7.0.1_softdevice.hex
	nrfjprog -f nrf52 --program $(NRF_PATH)/components/softdevice/s132/hex/s132_nrf52_7.0.1_softdevice.hex --sectorerase
	nrfjprog -f nrf52 --reset

erase:
	nrfjprog -f nrf52 --eraseall
