ASM := nasm

CC := x86_64-elf-gcc
CCFLAGS := 

LD := x86_64-elf-ld
LDFLAGS := 

INCLUDE := include/

# Target: kernel, type: C ASM
kernel_c_source_files = $(shell find src/kernel/ -type f -name *.c)
kernel_c_object_files = $(patsubst src/%.c,obj/%.o,$(kernel_c_source_files))
kernel_asm_source_files = $(shell find src/kernel/ -type f -name *.asm)
kernel_asm_object_files = $(patsubst src/%.asm,obj/%.o,$(kernel_asm_source_files))
kernel_source_files = $(kernel_c_source_files) $(kernel_asm_object_files)
kernel_object_files = $(kernel_c_object_files) $(kernel_asm_object_files)

# Target: libc, type: C ASM
libc_c_source_files = $(shell find src/libc/ -type f -name *.c)
libc_c_object_files = $(patsubst src/%.c,obj/%.o,$(libc_c_source_files))
libc_asm_source_files = $(shell find src/libc/ -type f -name *.asm)
libc_asm_object_files = $(patsubst src/%.asm,obj/%.o,$(libc_c_object_files))
libc_source_files = $(libc_c_source_files) $(libc_asm_source_files)
libc_object_files = $(libc_c_object_files) $(libc_asm_object_files)

# Target: sboot, type: ASM
# Override: 32-bit
sboot_asm_source_files = $(shell find src/boot/ -type f -name *.asm)
sboot_asm_object_files = $(patsubst src/%.asm,obj/%.o,$(sboot_asm_source_files))
sboot_source_files = $(sboot_asm_source_files)
sboot_object_files = $(sboot_asm_object_files)

shade_bin_ldfile = src/linker.ld

default: run

bin/shade.iso: bin/shade.bin
	cp bin/shade.bin src/iso/boot/shade.bin
	grub-mkrescue src/iso/ -o $@
	rm src/iso/boot/shade.bin

bin/shade.bin: $(sboot_object_files) $(kernel_object_files) $(libc_object_files)
	mkdir -p "$(@D)"
	$(LD) $(LDFLAGS) -n -T $(shade_bin_ldfile) $^ -o $@
	grub-file --is-x86-multiboot2 $@

# Generics
# Source file types: C ASM

# C
obj/%.o: src/%.c
	mkdir -p "$(@D)"
	$(CC) $(CCFLAGS) -I $(INCLUDE) -ffreestanding -c $< -o $@

# ASM
obj/%.o: src/%.asm
	mkdir -p "$(@D)"
	$(ASM) -felf64 $< -o $@

# Other
run: clean bin/shade.iso
	qemu-system-x86_64 -drive file=bin/shade.iso,index=0,media=disk,format=raw -d int -no-reboot

clean:
	rm -rf bin/*
	rm -rf obj/*