# Makefile — 两阶段最小内核（无 GRUB）
#
# 两套构建路径：
#   make / make run        —— C 内核版（Linux / WSL，需要 gcc + ld + objcopy）
#   make win / run-win     —— 纯汇编版（Windows，只需要 nasm）
# 两者产出同样的 disk.img（VGA + COM1 串口输出同一行字）。
#
# 依赖：
#   Linux/WSL: sudo apt install -y nasm gcc-multilib binutils qemu-system-i386 python3
#   Windows  : 只需 nasm + qemu-system-i386（qemu 装好后）
#
# 常用目标：
#   make run      构建 C 版并用 qemu 启动
#   make win      构建纯汇编版（Windows 无 gcc 时用）
#   make run-win  构建纯汇编版并用 qemu 启动
#   make clean    清理

NASM    ?= nasm
CC      ?= gcc
LD      ?= ld
OBJCOPY ?= objcopy
QEMU    ?= qemu-system-i386
PY      ?= python3

# C 内核：32 位、freestanding、关闭会引入麻烦的特性
CFLAGS   = -m32 -ffreestanding -fno-stack-protector -fno-pic \
           -fno-builtin -fno-asynchronous-unwind-tables -Wall -Wextra -O2 -c
LDFLAGS  = -m elf_i386 -T stage2.ld -nostdlib

IMAGE   = disk.img

.PHONY: all win run run-win clean

all: $(IMAGE)

# ---------- 第一阶段（两套构建共用） ----------
boot.bin: boot.asm
	$(NASM) -f bin boot.asm -o boot.bin

# ---------- C 内核版（Linux / WSL） ----------
stage2.bin: stage2.asm kernel.c acpi.c efi_fat.c stage2.ld
	$(NASM) -f elf32 stage2.asm -o stage2.o
	$(CC) $(CFLAGS) kernel.c -o kernel.o
	$(CC) $(CFLAGS) acpi.c -o acpi.o
	$(CC) $(CFLAGS) efi_fat.c -o efi_fat.o
	$(LD) $(LDFLAGS) stage2.o kernel.o acpi.o efi_fat.o -o stage2.elf
	$(OBJCOPY) -O binary stage2.elf stage2.bin
	@echo "stage2.bin = $$(wc -c < stage2.bin) bytes"

$(IMAGE): boot.bin stage2.bin
	$(PY) make_disk.py

run: $(IMAGE)
	$(QEMU) -fda $(IMAGE)

# ---------- 纯汇编版（Windows，只需 nasm） ----------
stage2_asm.bin: stage2_asm.asm
	$(NASM) -f bin stage2_asm.asm -o stage2_asm.bin

win: boot.bin stage2_asm.bin
	$(PY) make_disk.py --stage2 stage2_asm.bin

run-win: win
	$(QEMU) -fda $(IMAGE)

# ---------- C 内核（clang+lld，Windows/Linux 通用） ----------
win-clang:
	sh tools/build_c.sh

clean:
	rm -f boot.bin stage2.o kernel.o acpi.o switch.o stage2.elf stage2.bin stage2_asm.bin $(IMAGE)
