CROSS := i686-elf-
CC := $(CROSS)gcc
LD := $(CROSS)ld
QEMU := qemu-system-i386
MACHINE := pc-i440fx-7.2
BIOS := /usr/share/seabios/bios-256k.bin
QEMU_FLAGS := -machine $(MACHINE) -accel tcg -cpu qemu32 -smp 1 -m 64M -bios $(BIOS) -drive file=build/blank.img,format=raw,if=ide -boot order=c,strict=on -nic none -no-reboot
CFLAGS := -std=c11 -ffreestanding -O0 -g -Wall -Wextra -Werror -fno-pie -fno-stack-protector -fno-asynchronous-unwind-tables

.PHONY: build run debug check help
build: build/sample.elf build/blank.img

build/.dir:
	mkdir -p build
	touch $@

build/demo.o: sample/demo.c | build/.dir
	$(CC) $(CFLAGS) -c $< -o $@

build/entry.o: sample/entry.asm | build/.dir
	nasm -f elf32 -g -F dwarf $< -o $@

build/sample.elf: build/entry.o build/demo.o sample/linker.ld
	$(LD) -z noexecstack -T sample/linker.ld build/entry.o build/demo.o -o $@

build/blank.img: | build/.dir
	dd if=/dev/zero of=$@ bs=512 count=2048 status=none

run: build
	$(QEMU) $(QEMU_FLAGS) -nographic

debug: build
	$(QEMU) $(QEMU_FLAGS) -display none -serial none -monitor none -S -gdb tcp:127.0.0.1:1234

check: build
	QEMU='$(QEMU)' QEMU_FLAGS='$(QEMU_FLAGS)' sh tools/check.sh

help:
	@printf '%s\n' 'make build: ELF32 sample and unbootable blank disk' 'make run: BIOS boot attempt; Ctrl-a x exits QEMU' 'make debug: CPU paused, GDB on container loopback port 1234' 'make check: ELF, missing-symbol and QEMU/GDB checks'
