ASM ?= nasm
CC := x86_64-elf-gcc
GDB := gdb
LD := x86_64-elf-ld

C_FILES = $(shell find src/ -type f -name '*.c')
CO_FILES = $(patsubst src/%.c, obj/%.o, $(C_FILES))
ASM_FILES = $(shell find src/kernel/ -type f -name '*.asm')
AO_FILES = $(patsubst src/kernel/%.asm, obj/kernel/%.o, $(ASM_FILES))

KERNEL_O_FILES = ${CO_FILES} ${AO_FILES}

BOOT_O_FILES = obj/entry.o obj/entry64.o obj/mb2.o obj/vga-print.o
BOOT_SRC_FILES = obj/entry.asm obj/entry64.asm obj/mb2.asm obj/vga-print.asm

iso: bin/shade.iso

bin/shade.bin: ${BOOT_O_FILES} ${KERNEL_O_FILES}
	mkdir -p bin
	$(LD) -T src/linker.ld $^ -o $@
	grub-file --is-x86-multiboot2 bin/shade.bin

bin/shade.iso: bin/shade.bin
	mkdir -p isodir/boot/grub
	cp bin/shade.bin isodir/boot/shade.bin
	cp src/iso/grub.cfg isodir/boot/grub/grub.cfg
	grub-mkrescue -o bin/shade.iso isodir
	rm -rf isodir

obj/%.o: src/%.c
	mkdir -p "$(@D)"
	$(CC) -ffreestanding -O2 -Wall -Wextra -c $< -o $@

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


run: clean bin/shade.iso
	qemu-system-x86_64 -hdd bin/shade.iso -d int -no-reboot

debug: clean bin/shade.iso bin/shade.bin
	qemu-system-x86_64 -s -S -hdd bin/shade.iso -d int -no-reboot &
	${GDB} os-image.bin -ex "set arch i386:x86-64" -ex "symbol-file bin/shade.bin" -ex "target remote localhost:1234"


clean:
	find obj -type f -name '*.o' -exec rm {} +
	find obj -type f -name '*.bin' -exec rm {} +
	find bin -type f -name '*.o' -exec rm {} +
	find bin -type f -name '*.bin' -exec rm {} +
	find . -type f -name '*.dis' -exec rm {} +
	rm -f kernel.elf
	rm -rf isodir