# HDGL Substrate — metal build
# Requires: nasm >= 2.14, gcc, grub-mkrescue, mtools, cpio, gzip
# Produces: hdgl-substrate-metal.iso

CC      = gcc
NASM    = nasm
CFLAGS  = -std=gnu99 -O2 -Wall -Wextra
BUILD   = obj

.PHONY: all clean

all: hdgl-substrate-metal.iso

$(BUILD):
	mkdir -p $(BUILD)

$(BUILD)/phi_lattice.o: phi_lattice.asm | $(BUILD)
	$(NASM) -f elf64 $< -o $@

$(BUILD)/face_operator.o: face_operator.asm | $(BUILD)
	$(NASM) -f elf64 $< -o $@

$(BUILD)/face_alpine.o: face_alpine_dialect.c face_node.h | $(BUILD)
	$(CC) $(CFLAGS) -I. -c $< -o $@

$(BUILD)/face_tinycore.o: face_tinycore.c face_node.h | $(BUILD)
	$(CC) $(CFLAGS) -I. -c $< -o $@

$(BUILD)/substrate_main.o: substrate_main.c face_node.h | $(BUILD)
	$(CC) $(CFLAGS) -I. -c $< -o $@

substrate-init: $(BUILD)/substrate_main.o $(BUILD)/face_alpine.o \
                $(BUILD)/face_tinycore.o $(BUILD)/face_operator.o \
                $(BUILD)/phi_lattice.o
	$(CC) -static -o $@ $^ -lutil

initrd.gz: substrate-init lattice_init.sh
	@echo "Building initrd..."
	@mkdir -p initrd_work/lattice
	@cp substrate-init initrd_work/init
	@chmod 755 initrd_work/init
	@cp lattice_init.sh initrd_work/lattice/init.sh
	@chmod 755 initrd_work/lattice/init.sh
	@# Copy base TinyCore initrd first (provides busybox userland)
	@# Base initrd must be at base_initrd.gz — extract from TinyCore ISO
	@cd initrd_work && find . | cpio -H newc -o 2>/dev/null | gzip -9 > ../initrd.gz

hdgl-substrate-metal.iso: substrate-init initrd.gz grub.cfg
	@mkdir -p isoroot/boot/grub
	@cp initrd.gz isoroot/boot/initrd.gz
	@cp grub.cfg  isoroot/boot/grub/grub.cfg
	@# vmlinuz: copy from your Linux kernel (Ubuntu 6.8 or TinyCore 6.18)
	@grub-mkrescue -o $@ isoroot -- -volid "HDGL-SUBSTRATE"
	@echo "ISO: $@"

clean:
	rm -rf $(BUILD) substrate-init initrd.gz isoroot hdgl-substrate-metal.iso
