
arch ?= x86-64
rust_target := x86_64-unknown-linux-gnu

linker_script := src/linker.ld
grub_cfg := src/grub.cfg
kernel := kernel.bin
iso := os.iso


asm_source := $(wildcard src/*.asm)
asm_object := $(patsubst src/%.asm, \
	%.o, $(asm_source))
rust_object := target/$(rust_target)/debug/librust_kernel.a

.PHONY: all clean run debugrun iso

all: $(kernel)

run: $(iso)
	@qemu-system-x86_64 -hda $(iso)

debugrun: $(iso)
	@qemu-system-x86_64 -d int -no-reboot -hda $(iso)

$(iso): $(kernel) $(grub_cfg)
	@mkdir -p isofiles/boot/grub
	@cp $(kernel) isofiles/boot/kernel.bin
	@cp $(grub_cfg) isofiles/boot/grub
	@grub-mkrescue -o $(iso) isofiles 2> /dev/null

test:
	@cargo test

cargo:
	@cargo rustc --target $(rust_target) -- -Z no-landing-pads

$(kernel): cargo $(rust_object) $(asm_object) $(linker_script)
	@ld -n --gc-sections -T $(linker_script) -o $(kernel) $(asm_object) $(rust_object)

%.o: src/%.asm
	@nasm -f elf64 $< -o $@

clean:
	@rm -rf isofiles
	@rm -f *.o
	@rm -f kernel.bin
	@rm -f os.iso
	@cargo clean
