BUILD_DIR=build
CC = gcc
AS = nasm
LD = ld

SRC_DIR := src build/flanterm
C_SOURCES := $(shell find $(SRC_DIR) -type f -name '*.c')
C_OBJECTS := $(patsubst %.c,$(BUILD_DIR)/%.o,$(C_SOURCES))

ASM_SOURCES := $(shell find $(SRC_DIR) -type f -name '*.asm')
ASM_OBJECTS := $(patsubst %.asm,$(BUILD_DIR)/%asm.o,$(ASM_SOURCES))

CFLAGS += -Wall \
    -Wextra \
    -std=gnu11 \
    -ffreestanding \
    -fno-stack-protector \
    -fno-stack-check \
    -fno-lto \
    -fPIE \
    -m64 \
    -march=x86-64 \
    -mno-80387 \
    -mno-mmx \
    -mno-sse \
    -mno-sse2 \
    -mno-red-zone \
    -I ./include \
    -O0 \
    -ggdb3 \
    -g

LDFLAGS += -m elf_x86_64 \
    -nostdlib \
    -static \
    -pie \
    --no-dynamic-linker \
    -z text \
    -z max-page-size=0x1000 \
    -T linker.ld

NASMFLAGS = -f elf64 -g -F dwarf

all: amd64

deps:
	mkdir -p $(BUILD_DIR) || true
	rm -rf build/limine
	git clone https://github.com/limine-bootloader/limine.git --branch=v10.x-binary --depth=1 build/limine
	git clone https://codeberg.org/Limine/limine-protocol/ build/limine-protocol
	make -C build/limine
	cp build/limine-protocol/include/limine.h include/
	rm -rf build/flanterm
	git clone https://codeberg.org/mintsuki/flanterm build/flanterm
	rm -rf build/uACPI
	rm -rf include/uACPI
	git clone https://github.com/uACPI/uACPI.git build/uACPI

	mkdir include/uACPI

	cp -r build/uACPI/include/* include/

$(BUILD_DIR)/%.o: %.c
	mkdir -p $(dir $@)
	$(CC) -c $< -o $@ $(CFLAGS)

$(BUILD_DIR)/%asm.o: %.asm
	mkdir -p $(dir $@)
	$(AS) $< -o $@ $(NASMFLAGS)


amd64: $(C_OBJECTS) $(ASM_OBJECTS)
	$(LD) -o $(BUILD_DIR)/Neobbo.elf $(C_OBJECTS) $(ASM_OBJECTS) $(LDFLAGS)
	mkdir -p iso_root
	cp -v $(BUILD_DIR)/Neobbo.elf limine.conf build/limine/limine-bios.sys \
		build/limine/limine-bios-cd.bin build/limine/limine-uefi-cd.bin iso_root/
	mkdir -p iso_root/EFI/BOOT
	cp -v build/limine/BOOTX64.EFI iso_root/EFI/BOOT/
	cp -v build/limine/BOOTIA32.EFI iso_root/EFI/BOOT/
	xorriso -as mkisofs -b limine-bios-cd.bin \
			-no-emul-boot -boot-load-size 4 -boot-info-table \
			--efi-boot limine-uefi-cd.bin \
			-efi-boot-part --efi-boot-image --protective-msdos-label \
			iso_root -o $(BUILD_DIR)/Neobbo.iso
	./build/limine/limine bios-install $(BUILD_DIR)/Neobbo.iso

disk:
	dd if=/dev/zero of=disk.img bs=1M count=128

elftest:
	$(CC) src/elf/elftest.c -o $(BUILD_DIR)/elftest -ffreestanding -Isrc/include -static -fPIE -nostdlib

clean:
	rm -rf build/ iso_root
