# Define paths and files
IMAGE_SIZE_MB := 10
DISK_IMAGE := dist/x86_64/filesystem.img
KERNEL_BIN := dist/x86_64/kernel.bin
ISO_FILE := dist/x86_64/kernel.iso
ISO_DIR := targets/x86_64/iso

# List of object files
kernel_source_files := $(shell find src/impl/kernel -name *.c)
kernel_object_files := $(patsubst src/impl/kernel/%.c, build/kernel/%.o, $(kernel_source_files))

x86_64_c_source_files := $(shell find src/impl/x86_64 -name *.c)
x86_64_c_object_files := $(patsubst src/impl/x86_64/%.c, build/x86_64/%.o, $(x86_64_c_source_files))

x86_64_cpp_source_files := $(shell find src/impl/x86_64 -name *.cpp)
x86_64_cpp_object_files := $(patsubst src/impl/x86_64/%.cpp, build/x86_64/%.o, $(x86_64_cpp_source_files))

x86_64_asm_source_files := $(shell find src/impl/x86_64 -name *.asm)
x86_64_asm_object_files := $(patsubst src/impl/x86_64/%.asm, build/x86_64/%.o, $(x86_64_asm_source_files))

x86_64_object_files := $(x86_64_c_object_files) $(x86_64_cpp_object_files) $(x86_64_asm_object_files)

# Rule to compile C files for the kernel
$(kernel_object_files): build/kernel/%.o : src/impl/kernel/%.c
	mkdir -p $(dir $@) && \
	x86_64-elf-gcc -c -I src/intf -ffreestanding $(patsubst build/kernel/%.o, src/impl/kernel/%.c, $@) -o $@

# Rule to compile C files for x86_64
$(x86_64_c_object_files): build/x86_64/%.o : src/impl/x86_64/%.c
	mkdir -p $(dir $@) && \
	x86_64-elf-gcc -c -I src/intf -ffreestanding $(patsubst build/x86_64/%.o, src/impl/x86_64/%.c, $@) -o $@

# Rule to compile C++ files for x86_64
$(x86_64_cpp_object_files): build/x86_64/%.o : src/impl/x86_64/%.cpp
	mkdir -p $(dir $@) && \
	x86_64-elf-g++ -c -I src/intf -ffreestanding $(patsubst build/x86_64/%.o, src/impl/x86_64/%.cpp, $@) -o $@

# Rule to assemble ASM files for x86_64
$(x86_64_asm_object_files): build/x86_64/%.o : src/impl/x86_64/%.asm
	mkdir -p $(dir $@) && \
	nasm -f elf64 $(patsubst build/x86_64/%.o, src/impl/x86_64/%.asm, $@) -o $@

.PHONY: build-x86_64
build-x86_64: $(kernel_object_files) $(x86_64_object_files)
	mkdir -p dist/x86_64 targets/x86_64/iso && \
	x86_64-elf-ld -n -o $(KERNEL_BIN) -T targets/x86_64/linker.ld $(kernel_object_files) $(x86_64_object_files) && \
	cp $(KERNEL_BIN) $(ISO_DIR)/boot/kernel.bin && \
	dd if=/dev/zero of=$(DISK_IMAGE) bs=1M count=$(IMAGE_SIZE_MB) && \
	mkfs.vfat -F 16 $(DISK_IMAGE) && \
	mcopy -i $(DISK_IMAGE) filesystem/hello/hello.txt ::/ && \
	grub-mkrescue -o $(ISO_FILE) $(ISO_DIR)
