PREFIX = arm-none-eabi-
CC = $(PREFIX)gcc
AS = $(PREFIX)as
LD = $(PREFIX)ld
OBJCOPY = $(PREFIX)objcopy
SIZE = $(PREFIX)size

PROJECT = firmware
MCU = cortex-m4
FLASH_START = 0x00000000
LOAD_ADDRESS = 0x10002000
LD_FILE=linker.ld

RAM_START := 0x10002000

CFLAGS = -mcpu=$(MCU) -mthumb -mfloat-abi=hard -lm \
    -Wall -Wextra -g3 \
    -Os -ffunction-sections -fdata-sections \
    -nostartfiles -Wl,-T,$(LD_FILE) -u main -Wl,--gc-sections

ASFLAGS = -mcpu=$(MCU) -mthumb -g

LDFLAGS = -T linker.ld -Map=$(BUILD_DIR)/$(PROJECT).map \
    --gc-sections --no-warn-rwx-segments \
    --defsym=_RAM_START_ADDR=$(RAM_START)

SRC_DIR = src
BUILD_DIR = build
INCLUDE_DIR = include

# todo
INCLUDES = -I$(INCLUDE_DIR)

SRCS := $(wildcard $(SRC_DIR)/*.c) $(wildcard $(SRC_DIR)/*.s)
OBJS := $(patsubst $(SRC_DIR)/%.c,$(BUILD_DIR)/%.o,$(filter %.c,$(SRCS))) \
        $(patsubst $(SRC_DIR)/%.s,$(BUILD_DIR)/%.o,$(filter %.s,$(SRCS)))

ELF = $(BUILD_DIR)/$(PROJECT).elf
BIN = $(BUILD_DIR)/$(PROJECT).bin
HEX = $(BUILD_DIR)/$(PROJECT).hex

# flash
RTL8710_PATH = ./rtl8710_openocd
FLASH_BIN = $(BUILD_DIR)/$(PROJECT).bin

.PHONY: all clean flash size test mac dump dump0 full_erase restore restore_nae verify reset

all: $(BUILD_DIR) $(ELF) $(BIN) $(HEX) size

$(BUILD_DIR):
	mkdir -p $(BUILD_DIR)

$(BUILD_DIR)/%.o: $(SRC_DIR)/%.c
	@echo "CC $<"
	@$(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@

$(BUILD_DIR)/%.o: $(SRC_DIR)/%.s
	@echo "AS $<"
	@$(AS) $(ASFLAGS) -c $< -o $@

$(ELF): $(OBJS) $(ASM_OBJS)
	@echo "LD $@"
	@$(LD) $(LDFLAGS) -o $@ $^

$(BIN): $(ELF)
	@echo "OBJCOPY $@"
	@$(OBJCOPY) -O binary $< $@

$(HEX): $(ELF)
	@echo "OBJCOPY $@"
	@$(OBJCOPY) -O ihex $< $@

size: $(ELF)
	@echo
	@$(SIZE) $<

clean:
	rm -rf $(BUILD_DIR)

# flash tool
include $(RTL8710_PATH)/rtl8710-openocd.mk

# flash cmds
rtl-flash:
	@$(OPENOCD_BASE) -c 'rtl8710_flash_auto_erase 1' \
	-c 'rtl8710_flash_auto_verify 1' \
	-c 'rtl8710_flash_write $(FLASH_BIN) 0' \
	-c 'rtl8710_reboot' -c 'reset run' -c shutdown

.PHONY: rtl-test rtl-mac rtl-dump rtl-full-erase rtl-restore rtl-restore-nae rtl-verify rtl-reset rtl-flash clean
