PROJECT := agila-open-kernel
BUILD := build
OBJ := $(BUILD)/obj
BIN := $(BUILD)/bin
GPRBUILD := gprbuild
GPRCLEAN := gprclean

.PHONY: all clean rebuild run help

all:
	mkdir -p $(OBJ) $(BIN)
	$(GPRBUILD) -P kernel.gpr

clean:
	$(GPRCLEAN) -P kernel.gpr || true
	rm -rf $(BUILD)

rebuild: clean all

run: all
	$(BIN)/main

help:
	@echo "Agila Open Kernel"
	@echo "make          Build the host prototype"
	@echo "make run      Build and run the host prototype"
	@echo "make clean    Remove build output"
	@echo "make rebuild  Clean and rebuild"
	@echo "make test     Ada port, C ABI, and V client checks"
	@echo "make boot-test Build ISO and verify x86-64 QEMU boot"

V ?= v
CC ?= cc

.PHONY: test host-library v-demo

host-library:
	$(GPRBUILD) -p -P host_library.gpr

v-demo: host-library
	mkdir -p $(BIN) $(BUILD)/vmodules $(BUILD)/vtmp
	VMODULES="$(CURDIR)/$(BUILD)/vmodules" VTMP="$(CURDIR)/$(BUILD)/vtmp" $(V) -cc gcc -gc none -o $(BIN)/agila_port_client examples/v_port_client/main.v

$(BIN)/abi_test: tests/abi_test.c include/agila_ports.h host-library
	$(CC) -std=c17 -Wall -Wextra -Werror -Iinclude tests/abi_test.c -Lbuild/lib -lagila_host -o $@

test: all host-library v-demo $(BIN)/abi_test
	$(GPRBUILD) -p -P ports.gpr
	$(BIN)/ports_test
	LD_LIBRARY_PATH="$(CURDIR)/build/lib:$${LD_LIBRARY_PATH:-}" $(BIN)/abi_test
	LD_LIBRARY_PATH="$(CURDIR)/build/lib:$${LD_LIBRARY_PATH:-}" $(BIN)/agila_port_client

BOOT_FLAGS := -O2 -fno-pie -fno-stack-protector -mno-red-zone -mgeneral-regs-only -fno-asynchronous-unwind-tables
.PHONY: boot boot-test
boot:
	mkdir -p build/boot build/iso/boot/grub
	gcc $(BOOT_FLAGS) -c boot/start.S -o build/boot/start.o
	gcc $(BOOT_FLAGS) -ffreestanding -fno-builtin -c boot/memory.c -o build/boot/memory.o
	gnatmake -c -D build/boot -Icore -gnat2022 -gnatp $(BOOT_FLAGS) boot/boot_main.adb
	ld -nostdlib -z max-page-size=0x1000 -T boot/linker.ld -o build/open-agila.elf build/boot/start.o build/boot/boot_main.o build/boot/agila_ports.o build/boot/memory.o
	grub-file --is-x86-multiboot build/open-agila.elf
	cp build/open-agila.elf build/iso/boot/
	cp boot/grub.cfg build/iso/boot/grub/grub.cfg
	grub-mkrescue -d /usr/lib/grub/i386-pc -o build/open-agila.iso build/iso
boot-test: boot
	python3 scripts/boot-smoke.py
