BASE		= $(HOME)/extbuilds/avr8-gnu-toolchain-linux_x86_64
CC 		= $(BASE)/bin/avr-gcc
OBJDUMP		= $(BASE)/bin/avr-objdump
SIZE		= $(BASE)/bin/avr-size
OBJCOPY		= $(BASE)/bin/avr-objcopy
MCU_TARGET	= attiny412
F_CPU           = 20000000UL
PORT		= /dev/ttyUSB0
BAUD            = 115200

SUBDIRS = task hal
INCS    = -I.

# -Os is critical for 4KB Flash
# -MMD -MP generates the dependency .d files automatically
CFLAGS  = -mmcu=$(MCU_TARGET) -DF_CPU=$(F_CPU) -Os -Wall -Wextra -Werror -std=c99 
CFLAGS += -funsigned-char -funsigned-bitfields -fpack-struct -fshort-enums
CFLAGS += $(INCS) -MMD -MP

LDFLAGS = -mmcu=$(MCU_TARGET)

# Finds all .c files in the defined subdirectories
SRCS = $(foreach dir,$(SUBDIRS),$(wildcard $(dir)/*.c))
SRCS += main.c
OBJS = $(SRCS:.c=.o)
DEPS = $(SRCS:.c=.d)

TARGET = main

.PHONY: all clean size flash

all: $(TARGET).hex fuses.hex size

# Linking the ELF
$(TARGET).elf: $(OBJS)
	@echo "Linking $@"
	@$(CC) $(LDFLAGS) -o $@ $^

# Extract Flash Intel HEX (stripping eeprom, fuses, lockbits)
$(TARGET).hex: $(TARGET).elf
	@echo "Generating Flash hex: $@"
	@$(OBJCOPY) -O ihex -R .eeprom -R .fuse -R .lock -R .signature $< $@

# Extract Fuses Intel HEX from C code (hal_system.c FUSES struct)
fuses.hex: $(TARGET).elf
	@echo "Generating Fuses hex: $@"
	@$(OBJCOPY) -j .fuse --change-section-lma .fuse=0 -O ihex $< $@

# Extract EEPROM Intel HEX from C code (if EEMEM variables exist)
eeprom.hex: $(TARGET).elf
	@echo "Generating EEPROM hex: $@"
	@$(OBJCOPY) -j .eeprom --change-section-lma .eeprom=0 -O ihex $< $@

size: $(TARGET).elf
	@echo ""
	@$(SIZE) --mcu=$(MCU_TARGET) -C $<

# Flash via serial UPDI (avrdude) using hex files generated from C source code
flash: $(TARGET).hex fuses.hex size
	avrdude -c serialupdi -p $(MCU_TARGET) -P $(PORT) -b $(BAUD) \
		-U flash:w:$(TARGET).hex:i \
		-U fuses:w:fuses.hex:i

clean:
	@echo "Cleaning build artifacts..."
	@rm -f $(OBJS) $(DEPS) $(TARGET).elf $(TARGET).hex fuses.hex eeprom.hex


# Pulls in the .d files generated by -MMD
-include $(DEPS)
