# Makefile for libdialogs shared library on MontaukOS
# Copyright (c) 2026 Daniel Hammer

MAKEFLAGS += -rR
.SUFFIXES:

TOOLCHAIN_PREFIX := $(shell cd ../../.. && pwd)/toolchain/local/bin/x86_64-elf-
ifneq ($(wildcard $(TOOLCHAIN_PREFIX)gcc),)
    CC  := $(TOOLCHAIN_PREFIX)gcc
    CXX := $(TOOLCHAIN_PREFIX)g++
    LD  := $(TOOLCHAIN_PREFIX)ld
    STRIP := $(TOOLCHAIN_PREFIX)strip
else
    CC  := gcc
    CXX := g++
    LD  := ld
    STRIP := strip
endif

PROG_INC := ../../include
LIBOUTDIR := ../../bin/os
OBJDIR    := obj
LEGACY_APPDIR := ../../bin/apps/dialogs
LIBC_SRC := ../../lib/libc/libc.c
GCC_INCLUDE := $(shell $(CC) -print-file-name=include)

CXXFLAGS := \
    -std=gnu++20 \
    -g -O2 -pipe \
    -Wall \
    -Wextra \
    -Wno-unused-parameter \
    -Wno-unused-function \
    -nostdinc \
    -ffreestanding \
    -fno-stack-protector \
    -fno-stack-check \
    -fPIC \
    -fno-rtti \
    -fno-exceptions \
    -ffunction-sections \
    -fdata-sections \
    -m64 \
    -march=x86-64 \
    -msse \
    -msse2 \
    -mno-red-zone \
    -mcmodel=small \
    -MMD -MP \
    -DGUI_DIALOGS_LIBRARY_BUILD \
    -I $(PROG_INC) \
    -isystem $(PROG_INC)/libc \
    -I ../../lib/bearssl/inc \
    -isystem ../../../kernel/freestnd-c-hdrs/x86_64/include \
    -isystem ../../../kernel/freestnd-cxx-hdrs/x86_64/include

LDFLAGS := \
    -shared \
    --build-id=none \
    --gc-sections \
    --hash-style=sysv \
    -u dialogs_run_request \
    -u dialogs_message_box \
    -m elf_x86_64 \
    -z max-page-size=0x1000

LIBC_CFLAGS := \
    -std=gnu11 \
    -g -O2 -pipe \
    -Wall \
    -Wno-unused-parameter \
    -nostdinc \
    -ffreestanding \
    -fno-stack-protector \
    -fno-stack-check \
    -fPIC \
    -ffunction-sections \
    -fdata-sections \
    -m64 \
    -march=x86-64 \
    -msse \
    -msse2 \
    -mno-red-zone \
    -mcmodel=small \
    -isystem $(PROG_INC)/libc \
    -isystem $(GCC_INCLUDE)

SRCS := main.cpp filedialog.cpp printdialog.cpp messagebox.cpp stb_truetype_impl.cpp font_data.cpp
OBJS := $(addprefix $(OBJDIR)/,$(SRCS:.cpp=.o))
LIBC_PIC_OBJ := $(OBJDIR)/libc_pic.o

TARGET := $(LIBOUTDIR)/libdialogs.lib

.PHONY: all clean

all: $(TARGET)

$(TARGET): $(OBJS) $(LIBC_PIC_OBJ) Makefile
	mkdir -p $(LIBOUTDIR)
	rm -rf $(LEGACY_APPDIR)
	$(LD) $(LDFLAGS) $(OBJS) $(LIBC_PIC_OBJ) -o $@
	$(STRIP) --strip-debug $@

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

$(LIBC_PIC_OBJ): $(LIBC_SRC) Makefile
	mkdir -p $(OBJDIR)
	$(CC) $(LIBC_CFLAGS) -c $(LIBC_SRC) -o $@

-include $(OBJS:.o=.d)

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