# compiler
CC = gcc
LD = ld

# flags
CFLAGS = -Wall -Wextra -std=c11 -ffreestanding -fno-stack-protector -fno-stack-check -fno-lto -fPIE -m64 -march=x86-64 -mno-80387 -mno-mmx -mno-sse -mno-sse2 -mno-red-zone -Isrc
LDFLAGS = -T linker.ld -static -nostdlib -no-pie -z max-page-size=0x1000

# files - This now finds EVERYTHING in src/ so your 1000 lines actually compile
SRCS = $(shell find src -name '*.c')
OBJS = $(patsubst src/%.c, build/%.o, $(SRCS))

# build
all: Fflorid.iso

# This rule handles creating subdirectories in build/ automatically
build/%.o: src/%.c
	mkdir -p $(dir $@)
	$(CC) $(CFLAGS) -c $< -o $@

iso_root/kernel: $(OBJS)
	$(LD) $(LDFLAGS) $(OBJS) -o iso_root/kernel

Fflorid.iso: iso_root/kernel
	# 1. DELETE any old config to prevent "shish kebab" ghosts
	rm -f iso_root/limine.cfg iso_root/boot/limine/limine.cfg
	
	# 2. FORCE-CREATE the config in the two safest spots
	# (Note: Using -e in echo for proper newlines)
	echo -e "TIMEOUT=3\n\n:Florid OS\n    PROTOCOL=limine\n    KERNEL_PATH=boot:///kernel" > iso_root/limine.cfg
	mkdir -p iso_root/boot/limine
	cp iso_root/limine.cfg iso_root/boot/limine/limine.cfg
	
	# 3. ENSURE the kernel is in the path defined above
	mkdir -p iso_root/boot
	cp iso_root/kernel iso_root/boot/kernel
	
	# 4. BUILD the ISO
	xorriso -as mkisofs -b limine/limine-bios-cd.bin \
		-no-emul-boot -boot-load-size 4 -boot-info-table \
		iso_root -o $@
	
	# 5. INSTALL Limine bios stages
	./iso_root/limine/limine bios-install $@

# clean - Nukes everything so you get a truly fresh start
clean:
	rm -rf build Fflorid.iso florid.iso iso_root/kernel