# MinGW-w64 cross build for Emu48+ Service Pack 68 (Linux/WSL host)
#
#   make                                  build/i686-w64-mingw32/Emu48.exe
#   make PREFIX=x86_64-w64-mingw32        build/x86_64-w64-mingw32/Emu48.exe
#   make OUT=/some/dir                    build there instead
#   make V=1                              echo the compiler command lines
#   make clean
#
# Emu48+ ships one project file, EMU48.DSP (the Emu48.dll variant has its
# own, EMU48DLL.DSP, and is not built here).  This mirrors its "Emu48 - Win32
# Release Unicode" configuration: the translation units in project order
# (apple.c is what Emu48+ adds to Emu48), preprocessor definitions
# NDEBUG;_UNICODE;UNICODE;WIN32;_WINDOWS;STRICT;REGISTRY, the per-file
# LODEPNG_NO_COMPILE_* set for lodepng.c, and the link libraries of the
# Release configuration.  The lodepng defines and the libraries match the
# GCC Makefile Christoph Gießelink ships for Emu48 in P48GCC68.ZIP (which
# builds the non-Unicode variant with its own resource script).
#
# The emulator sources are not rewritten for the build.  On a case-sensitive
# filesystem the MSVC-era spelling of the includes ("pch.h" for PCH.H,
# "io.h" for IO.H, <DSound.h> for dsound.h ...) needs forwarding headers,
# and the resource script names its files in lower case.  Both are handled
# in the build directory only.  See MINGW.md.

APP      := Emu48
RC       := EMU48.RC
SRCS     := APPLE CURSOR DDESERV DEBUGGER DISASM DISMEM DISPLAY DISRPL EMU48 \
            ENGINE FETCH FILES I28F160 KEYBOARD KEYMACRO KML LODEPNG LOWBAT \
            MOPS MRU OPCODES PCH PNGCRC REDEYE ROMCRC RPL SERIAL SETTINGS \
            SNDENUM SOUND STACK SYMBFILE TIMER UDP
LODEPNG_DEFINES := -DLODEPNG_NO_COMPILE_ENCODER -DLODEPNG_NO_COMPILE_DISK \
                   -DLODEPNG_NO_COMPILE_ANCILLARY_CHUNKS \
                   -DLODEPNG_NO_COMPILE_ERROR_TEXT -DLODEPNG_NO_COMPILE_CPP \
                   -DLODEPNG_NO_COMPILE_CRC
# as in the Emu48 GCC Makefile (P48GCC68.ZIP); -luuid for the COM IIDs the
# MSVC link picks up implicitly (SNDENUM.C)
LIBS     := -lwinmm -lcomctl32 -lws2_32 -luuid

# The SD card of the 49g+/50g (SDCARD.C): a FAT16 image file (FAT16.C) and
# the selectors of the Saturnator that reach it
SRCS += FAT16 SDCARD
# ---- common part: identical in Emu48+, Emu42, Emu28 and Emu71 ----------------

PREFIX   ?= i686-w64-mingw32
CC       := $(PREFIX)-gcc
WINDRES  := $(PREFIX)-windres
OBJDUMP  := $(PREFIX)-objdump
OUT      := $(abspath $(or $(OUT),build/$(PREFIX)))
# V=1 echoes the command lines
Q        := $(if $(V),,@)
# MinGW-w64 system headers; the sources spell two of them with upper-case letters.
SYSDIR   ?= /usr/share/mingw-w64/include

DEFINES  := -DNDEBUG -DUNICODE -D_UNICODE -DWIN32 -D_WINDOWS -DSTRICT -DREGISTRY

# -x c                  .C/.H are C, not C++
# -O2                   the project builds with /O2
# -fno-strict-aliasing  the Saturn core reads registers through casted
#                       pointers (REG() in OPCODES.C); MSVC does not reorder
#                       these, GCC at -O2 may
# -finput-charset -fexec-charset
#                       the sources are Windows-1252 (Emu28 and Emu42 hold HP
#                       display glyphs in DISPNUM.C as character constants);
#                       MSVC reads and emits them unchanged, GCC would assume
#                       UTF-8
# -g0 -fno-ident -ffile-prefix-map, -Wl,--no-insert-timestamp
#                       no compiler version, timestamp or build path in the
#                       output, so two builds of one commit are byte-identical
CFLAGS   := -x c -O2 -g0 -fno-ident -fno-strict-aliasing \
            -finput-charset=CP1252 -fexec-charset=CP1252 \
            -ffile-prefix-map=$(CURDIR)=.
# -mwindows             GUI subsystem; -static-libgcc: no LIBGCC DLL needed; the
#                       console test programs link with the timestamp flag alone
LDFLAGS  := -mwindows -static-libgcc -s -Wl,--no-insert-timestamp

# Windows system DLLs the executable may import (lower case, grep -E).
SYSTEM_DLLS_RE := ^(kernel32|user32|gdi32|comdlg32|comctl32|shell32|shlwapi|advapi32|winmm|ws2_32|ole32|oleaut32|uuid|msvcrt|ntdll)\.dll$$

OBJS     := $(addprefix $(OUT)/obj/,$(addsuffix .o,$(SRCS)))
RES      := $(OUT)/obj/$(APP).res.o
EXE      := $(OUT)/$(APP).exe

.PHONY: all check clean
all: check

# compile one translation unit; -MMD -MP records the headers it uses in a
# .d file next to the object (read below), so a header change rebuilds it
DEPFLAGS = -MMD -MP -MF $(@:.o=.d)

$(OUT)/obj/%.o: %.C Makefile | $(OUT)/.shims
	$(Q)$(CC) $(CFLAGS) $(DEPFLAGS) $(DEFINES) -iquote $(OUT)/inc -I$(OUT)/sysinc -I. -c $< -o $@

$(OUT)/obj/LODEPNG.o: LODEPNG.C Makefile | $(OUT)/.shims
	$(Q)$(CC) $(CFLAGS) $(DEPFLAGS) $(DEFINES) $(LODEPNG_DEFINES) -iquote $(OUT)/inc -I. -c $< -o $@

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

# forwarding headers for every include whose on-disk name differs only in case
$(OUT)/.shims: $(wildcard *.C *.H) Makefile
	@mkdir -p $(OUT)/inc $(OUT)/sysinc $(OUT)/obj
	@rm -f $(OUT)/inc/* $(OUT)/sysinc/*
	@for inc in `grep -a -h -o -E '#[[:space:]]*include[[:space:]]*"[^"]+"' *.C *.H \
	                | sed 's/.*"\([^"]*\)"/\1/' | sort -u`; do \
	    if [ ! -e "$$inc" ]; then \
	        real=`ls | grep -ixF -- "$$inc" | head -n1`; \
	        if [ -n "$$real" ]; then \
	            echo "#include \"$$real\"" > $(OUT)/inc/$$inc; \
	        fi; \
	    fi; \
	done
	@for inc in `grep -a -h -o -E '#[[:space:]]*include[[:space:]]*<[^>]+>' *.C *.H \
	                | sed 's/.*<\([^>]*\)>/\1/' | sort -u`; do \
	    if [ ! -e "$(SYSDIR)/$$inc" ]; then \
	        real=`ls $(SYSDIR) | grep -ixF -- "$$inc" | head -n1`; \
	        if [ -n "$$real" ]; then \
	            echo "#include <$$real>" > $(OUT)/sysinc/$$inc; \
	        fi; \
	    fi; \
	done
	@touch $@

# the resource script names its files ("resource.h", "checkbox.bmp", ...) in
# lower case: build from a copy that uses the on-disk spellings
$(OUT)/$(RC): $(RC) Makefile
	@mkdir -p $(OUT)
	@cp $(RC) $@.tmp
	@for name in `grep -a -o -E '"[^"]+\.(bmp|ico|xml|cur|png|h)"' $(RC) \
	                | tr -d '"' | sort -u`; do \
	    if [ ! -e "$$name" ]; then \
	        real=`ls | grep -ixF -- "$$name" | head -n1`; \
	        if [ -n "$$real" ]; then \
	            sed -i "s/\"$$name\"/\"$$real\"/g" $@.tmp; \
	        fi; \
	    fi; \
	done
	@mv $@.tmp $@

$(RES): $(OUT)/$(RC) RESOURCE.H $(wildcard *.BMP *.ICO *.XML)
	$(Q)$(WINDRES) --include-dir=$(SYSDIR) --include-dir=. -i $< -O coff -o $@

$(EXE): $(OBJS) $(RES)
	$(Q)$(CC) $(LDFLAGS) -o $@ $(OBJS) $(RES) $(LIBS)

# build, then verify the executable: a GUI-subsystem PE that imports from
# Windows system DLLs only; print its digest
check: $(EXE)
	@file $<
	@file $< | grep -Eq 'PE32(\+)? executable \(GUI\)' || { \
	    echo "$<: not a GUI-subsystem PE executable" >&2; exit 1; }
	@$(OBJDUMP) -p $< | sed -n 's/^[[:space:]]*DLL Name: /  imports /p'
	@bad=`$(OBJDUMP) -p $< | sed -n 's/^[[:space:]]*DLL Name: //p' \
	        | tr 'A-Z' 'a-z' | grep -Ev '$(SYSTEM_DLLS_RE)'`; \
	    if [ -n "$$bad" ]; then \
	        echo "$<: imports from non-system DLLs:" $$bad >&2; exit 1; \
	    fi
	@sha256sum $<

clean:
	rm -rf $(OUT)

# The SD card of the 49g+/50g (FAT16.C, SDCARD.C).  The file system runs on the
# host over a card in memory (tests/fat16_test.c); the card selectors run as a
# Windows console program over the runtime objects of the build, with the
# registers the firmware's own wrappers set up (tests/sdcard_test.c).
#   make testfat16    build and run the file system tests on the host
#   make testsdcard   build $(OUT)/sdcard_test.exe to run the selectors on Windows
HOSTCC ?= cc
.PHONY: testfat16 testsdcard
testfat16: $(OUT)/fat16_test
	$(OUT)/fat16_test

$(OUT)/fat16_test: tests/fat16_test.c FAT16.C FAT16.H
	@mkdir -p $(OUT)
	$(HOSTCC) -x c -std=c99 -Wall -Wextra -Werror -I. -iquote tests/win tests/fat16_test.c FAT16.C -o $@

testsdcard: $(OUT)/sdcard_test.exe
$(OUT)/sdcard_test.exe: tests/sdcard_test.c $(OBJS)
	$(CC) $(CFLAGS) -municode -g $(DEFINES) -iquote $(OUT)/inc -I$(OUT)/sysinc -I. -c $< -o $(OUT)/sdcard_test.o
	$(CC) -municode -mconsole -g -static-libgcc -Wl,--no-insert-timestamp -o $@ $(OUT)/sdcard_test.o $(OBJS) $(LIBS) -lgdi32 -lcomdlg32

# The opcodes 81B8 to 81BE and the BUSCC selectors of the ARM-based calculators
# against the Saturnator itself: tests/saturnator-vectors.txt holds Saturn
# states and what the ARM program of a flash container made of them.  The tool
# tools/saturnator-oracle.py writes the file with Unicorn, over a container that
# stays outside the tree; a Windows console program replays every line through
# the emulator's decoder (tests/oracle_test.c).
#   make testoracle   build $(OUT)/oracle_test.exe to replay them on Windows
.PHONY: testoracle
testoracle: $(OUT)/oracle_test.exe
$(OUT)/oracle_test.exe: tests/oracle_test.c tests/saturnator-vectors.txt $(OBJS)
	$(CC) $(CFLAGS) -municode -g $(DEFINES) -iquote $(OUT)/inc -I$(OUT)/sysinc -I. -c $< -o $(OUT)/oracle_test.o
	$(CC) -municode -mconsole -g -static-libgcc -Wl,--no-insert-timestamp -o $@ $(OUT)/oracle_test.o $(OBJS) $(LIBS) -lgdi32 -lcomdlg32

# The restart in place of the ARM hardware tests of the 49g+/50g (APPLE.C, BUSCC
# 14): a Windows console program over the runtime objects runs the selector through
# the decoder for the models that have it (tests/autotest_test.c); the firmware's
# own way there, ON with F4, F5 or F6 held, needs a ROM and was run under Wine.
#   make testautotest   build $(OUT)/autotest_test.exe
.PHONY: testautotest
testautotest: $(OUT)/autotest_test.exe
$(OUT)/autotest_test.exe: tests/autotest_test.c $(OBJS)
	$(CC) $(CFLAGS) -municode -g $(DEFINES) -iquote $(OUT)/inc -I$(OUT)/sysinc -I. -c $< -o $(OUT)/autotest_test.o
	$(CC) -municode -mconsole -g -static-libgcc -Wl,--no-insert-timestamp -o $@ $(OUT)/autotest_test.o $(OBJS) $(LIBS) -lgdi32 -lcomdlg32

# Run the ROM's ON+C and PINIT with a fresh document, with SD, after detach,
# and after reopening the attached document. Supply an installed calculator KML.
#   sd_warmstart_test.exe path/to/model.kml 16    (repeat with 1024)
.PHONY: testwarmstart
testwarmstart: $(OUT)/sd_warmstart_test.exe
$(OUT)/sd_warmstart_test.exe: tests/sd_warmstart_test.c EMU48.C $(OBJS) $(EXE)
	$(CC) $(CFLAGS) -municode $(DEFINES) -iquote $(OUT)/inc -I$(OUT)/sysinc -I. -c $< -o $(OUT)/sd_warmstart_test.o
	$(CC) -municode -mconsole -static-libgcc -Wl,--no-insert-timestamp,--wrap=Nread,--wrap=DisplayChooseKml -o $@ $(OUT)/sd_warmstart_test.o $(filter-out $(OUT)/obj/EMU48.o,$(OBJS)) $(LIBS) -lgdi32 -lcomdlg32
