# $@ = target file
# $< = first dependency
# $^ = all dependencies

GDB = gdb

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))
ABIN_FILES = $(patsubst src/%.asm, bin/%.bin, $(ASM_FILES))

os-image.bin: bin/boot.bin bin/kernel.bin
	cat $^ > $@

bin/boot.bin: src/boot/boot.asm bin/kernel.bin .FORCE
	sed -i.orig "s@CH_REPLACE_BOOTSECTORCOUNT@$(shell ./getinblocks.py $(shell du -b "bin/kernel.bin" | cut -f 1))@g" src/boot/kernel.asm
	nasm -Isrc/boot/ $< -f bin -o $@
	mv src/boot/kernel.asm.orig src/boot/kernel.asm

.FORCE:

bin/kernel.bin: obj/kernel/entry.o ${CO_FILES} ${AO_FILES}
	i386-elf-ld -o $@ -Ttext 0x1000 $^ --oformat binary

kernel.elf: obj/kernel/entry.o ${CO_FILES} ${AO_FILES}
	i386-elf-ld -o $@ -Ttext 0x1000 $^

run: clean os-image.bin
	qemu-system-x86_64 -hdd os-image.bin -d int

debug: clean os-image.bin kernel.elf
	qemu-system-x86_64 -s -S -hdd os-image.bin &
	${GDB} os-image.bin -ex "symbol-file kernel.elf" -ex "target remote localhost:1234"



obj/%.o: src/%.c
	mkdir -p "$(@D)"
	i386-elf-gcc -g -ffreestanding -c $< -o $@

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

bin/%.bin: src/%.asm
	mkdir -p "$(@D)"
	nasm -f bin $< -o $@

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