PREFIX   ?= arm-none-eabi-
CC        = $(PREFIX)gcc
OBJCOPY   = $(PREFIX)objcopy
SIZE      = $(PREFIX)size

PNAME    := blink
BUILD    := build

# libopencm3 is provided by the Nix shell
OPENCM3_DIR ?= ""

SRCS     := src/main.c
OBJS     := $(addprefix $(BUILD)/, $(SRCS:.c=.o))

# STM32G4
CPU_FLAGS := -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16

CFLAGS   := $(CPU_FLAGS) \
            -DSTM32G4 \
            -Os -Wall -Wextra \
            -ffunction-sections -fdata-sections \
            -I$(OPENCM3_DIR)/include

LDFLAGS  := $(CPU_FLAGS) \
            -nostartfiles \
            -Wl,--gc-sections \
            -L$(OPENCM3_DIR)/lib \
            -lopencm3_stm32g4

ELF := $(BUILD)/$(PNAME).elf
BIN := $(BUILD)/$(PNAME).bin
HEX := $(BUILD)/$(PNAME).hex

.PHONY: all clean flash size

all: $(BIN) $(HEX) size

$(BUILD)/%.o: %.c
	@mkdir -p $(@D)
	$(CC) $(CFLAGS) -c $< -o $@

LDSCRIPT := $(BUILD)/stm32g474xe.ld

$(LDSCRIPT):
	@mkdir -p $(@D)
	$(CC) -I$(OPENCM3_DIR)/include $(shell python3 $(OPENCM3_DIR)/scripts/genlink.py $(OPENCM3_DIR)/ld/devices.data stm32g474xe DEFS) -P -E $(OPENCM3_DIR)/ld/linker.ld.S -o $@

$(ELF): $(OBJS) $(LDSCRIPT)
	$(CC) $(OBJS) $(LDFLAGS) -T$(LDSCRIPT) -o $@

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

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

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

flash: $(BIN)
	openocd \
	  -f interface/stlink.cfg \
	  -f target/stm32g4x.cfg \
	  -c "program $(BIN) verify reset exit 0x08000000"

clean:
	rm -rf $(BUILD)
