# Makefile for firstboot (Raspberry Pi first-boot volume grow) on MontaukOS
# Copyright (c) 2026 Daniel Hammer
#
# Only the Raspberry Pi SD image ships this program, so it is built into
# bin<arch>-rpi/ rather than bin<arch>/: everything under bin<arch>/ goes into
# the ramdisk. scripts/mk-rpi4-sd.sh lays bin<arch>-rpi/ over the system tree.

MAKEFLAGS += -rR
.SUFFIXES:

# ---- Toolchain ----

include ../../mk/arch.mk
ifeq ($(wildcard $(TOOLCHAIN_PREFIX)gcc),)
    CXX = $(error $(TOOLCHAIN_MISSING))
else
    CXX := $(TOOLCHAIN_PREFIX)g++
endif

# ---- Paths ----

PROG_INC := ../../include
LIBC_LIB := ../../lib/libc
LINK_LD  := ../../link.ld
BINDIR   := ../../bin$(ARCH_SUFFIX)-rpi
OBJDIR   := obj$(ARCH_SUFFIX)
# The login screen's font support, shared rather than copied.
LOGIN    := ../login

# ---- Compiler flags ----

CXXFLAGS := \
    -std=gnu++20 \
    -g -O2 -pipe \
    -Wall \
    -Wextra \
    -Wno-unused-parameter \
    -Wno-unused-function \
    -ffreestanding \
    -fno-stack-protector \
    -fno-stack-check \
    -fno-rtti \
    -fno-exceptions \
    -ffunction-sections \
    -fdata-sections \
    $(ARCH_FP_FLAGS) \
    -I $(PROG_INC) \
    -isystem $(PROG_INC)/libc

# ---- Linker flags ----

LDFLAGS := \
    -nostdlib \
    -Wl,--gc-sections \
    -T $(LINK_LD)

# ---- Source files ----

OBJS := $(OBJDIR)/main.o $(OBJDIR)/font_data.o $(OBJDIR)/stb_truetype_impl.o
DEPS := $(OBJS:.o=.d)

# ---- Target ----

TARGET := $(BINDIR)/os/firstboot.elf

.PHONY: all clean

all: $(TARGET)

LIBS := $(LIBC_LIB)/$(ARCH_OUT)liblibc.a

$(TARGET): $(OBJS) $(LIBS) $(LINK_LD) Makefile
	mkdir -p $(BINDIR)/os
	$(CXX) $(CXXFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@

$(OBJDIR)/%.o: %.cpp Makefile
	mkdir -p $(OBJDIR)
	$(CXX) $(CXXFLAGS) -MMD -MP -c $< -o $@

$(OBJDIR)/%.o: $(LOGIN)/%.cpp Makefile
	mkdir -p $(OBJDIR)
	$(CXX) $(CXXFLAGS) -MMD -MP -c $< -o $@

-include $(DEPS)

clean:
	rm -rf $(OBJDIR) $(TARGET)
