# Used to generated .d file that deal with header dependencies
CPPFLAGS = -MMD
AS=nasm
ASFLAGS += -f elf32
#LDFLAGS += -m32 -nostdlib -mkernel -fno-stack-protector
LDFLAGS += -m32 -nostdlib -static -fno-common -fno-use-cxa-atexit -fno-exceptions -fno-non-call-exceptions -fno-weak -fno-rtti -fno-stack-protector
CFLAGS += -m32 -Wall -Wextra -Werror -ffreestanding -fno-exceptions -fno-pie -fno-stack-protector -fno-tree-vectorize
CXXFLAGS += -m32 -Wall -Wextra -Werror -ffreestanding -fno-exceptions -fno-rtti -fno-pie
DEBUG_FLAGS += -g -Og -DDEBUG -fno-omit-frame-pointer -fno-inline

QEMU_OPT += -hda disk.img
ARCH?=x86
SUBDIRS := core drivers tests arch/$(ARCH)

CPPFLAGS += $(foreach dir, $(SUBDIRS), -I$(dir))

asmsrc=$(wildcard arch/$(ARCH)/boot/*.asm)
asmobj=$(asmsrc:%.asm=%.o)
csrc=$(shell find $(SUBDIRS) -type f -name "*.c")#   $(wildcard *.c)
cobj=$(csrc:%.c=%.o) arch/$(ARCH)/cpu_context_switch.o arch/$(ARCH)/irq_pit.o
deps = $(csrc:%.c=%.d)

kernel kernel.sym &: $(asmobj) $(cobj) linker.ld
	$(CC) -m32  -ffreestanding -nostdlib $(cobj) $(asmobj) -o kernel -T linker.ld -lgcc
	objcopy --only-keep-debug kernel kernel.sym
	objcopy --strip-debug  kernel

fd.iso: kernel
	mkdir -p isodir/boot/grub
	cp $< isodir/boot/
	@printf "menuentry \"myos\" {\n\tmultiboot /boot/kernel\n}" > isodir/boot/grub/grub.cfg
	grub-mkrescue -o $@ isodir

disk.img:
	qemu-img create -f qcow2 disk.img 32M

#https://gcc.gnu.org/onlinedocs/gcc/x86-Function-Attributes.html#x86-Function-Attributes
arch/$(ARCH)/exception_handler.o:arch/$(ARCH)/exception_handler.c
	$(CC) $(CFLAGS) $(CPPFLAGS) -mgeneral-regs-only  -c $< -o $@
arch/$(ARCH)/irq_handler.o:arch/$(ARCH)/irq_handler.c
	$(CC) $(CFLAGS) $(CPPFLAGS) -mgeneral-regs-only  -c $< -o $@

%.o:%.asm
	$(AS) $(ASFLAGS) -o $@ $<

%.o: %.S
	$(CC) "-I$(PWD)" -c "$<" $(CFLAGS) -o "$@"


test: CFLAGS += -DRUN_TEST
test: clean kernel disk.img
	qemu-system-x86_64 -kernel kernel -serial stdio -m 32M $(QEMU_OPT)

run:kernel disk.img
	qemu-system-x86_64 -kernel $< $(QEMU_OPT)

debug: CFLAGS += $(DEBUG_FLAGS) -DRUN_TEST
debug: CXXFLAGS += $(DEBUG_FLAGS)
debug:kernel kernel.sym
	#qemu-system-x86_64 -s -S -kernel kernel&
	#qemu-system-i386 -s -S -kernel kernel&
	#gdb -s kernel.sym -ex "target remote localhost:1234" -ex "dir core:driver:arch/$(ARCH))'"
	gdb -x debug.gdb

debug_test: CFLAGS += $(DEBUG_FLAGS) -DRUN_TEST
debug_test: debug

clean:
	$(RM) kernel $(asmobj) $(cobj) $(deps) fd.iso kernel.sym
	$(RM) -r isodir

ifneq ($(MAKECMDGOALS),clean)
-include $(deps)
endif