CC ?= cc
CFLAGS ?= -O2 -Wall -Wextra -std=c99
PREFIX ?= /usr/local
BINDIR ?= $(PREFIX)/bin
DATADIR ?= $(PREFIX)/share
ASSETDIR = $(DATADIR)/armored-snake
DESTDIR ?=
SDL_CFLAGS := $(shell pkg-config --cflags sdl3)
SDL_LIBS := $(shell pkg-config --libs sdl3)
DATA_DEFINE = -DARMORED_SNAKE_DATADIR=\"$(ASSETDIR)\"

all: armored-snake
armored-snake: main.c controls.c controls.h snake_audio.c snake_audio.h
	$(CC) $(CFLAGS) $(DATA_DEFINE) $(SDL_CFLAGS) main.c controls.c snake_audio.c -o $@ $(SDL_LIBS) -lm

test_balance: test_balance.c main.c controls.c controls.h snake_audio.c snake_audio.h
	$(CC) $(CFLAGS) $(DATA_DEFINE) $(SDL_CFLAGS) test_balance.c controls.c snake_audio.c -o $@ $(SDL_LIBS) -lm
check: test_balance
	./test_balance
install: armored-snake
	install -d "$(DESTDIR)$(BINDIR)" "$(DESTDIR)$(ASSETDIR)/assets" "$(DESTDIR)$(DATADIR)/applications" "$(DESTDIR)$(DATADIR)/icons/hicolor/256x256/apps"
	install -m 755 armored-snake "$(DESTDIR)$(BINDIR)/armored-snake"
	install -m 644 assets/*.rgba "$(DESTDIR)$(ASSETDIR)/assets/"
	install -m 644 armored-snake.desktop "$(DESTDIR)$(DATADIR)/applications/armored-snake.desktop"
	install -m 644 icons/armored-snake-256.png "$(DESTDIR)$(DATADIR)/icons/hicolor/256x256/apps/armored-snake.png"
uninstall:
	rm -f "$(DESTDIR)$(BINDIR)/armored-snake"
	rm -f "$(DESTDIR)$(DATADIR)/applications/armored-snake.desktop"
	rm -f "$(DESTDIR)$(DATADIR)/icons/hicolor/256x256/apps/armored-snake.png"
	rm -rf "$(DESTDIR)$(ASSETDIR)"
clean:
	rm -f armored-snake test_balance
.PHONY: all check clean install uninstall

# Windows cross-build. Requires a matching SDL3 MinGW-w64 developer SDK.
MINGW_CC ?= x86_64-w64-mingw32-gcc
WINDRES ?= x86_64-w64-mingw32-windres
SDL3_MINGW_ROOT ?=
WIN_DIST := dist/windows
windows:
	@test -n "$(SDL3_MINGW_ROOT)" || (echo "Set SDL3_MINGW_ROOT=/path/to/SDL3-mingw-x64-sdk"; exit 1)
	@test -f "$(SDL3_MINGW_ROOT)/include/SDL3/SDL.h" || (echo "Missing SDL3 headers"; exit 1)
	@test -f "$(SDL3_MINGW_ROOT)/lib/libSDL3.dll.a" || (echo "Missing SDL3 import library"; exit 1)
	@test -f "$(SDL3_MINGW_ROOT)/bin/SDL3.dll" || (echo "Missing SDL3.dll"; exit 1)
	mkdir -p "$(WIN_DIST)/assets"
	$(WINDRES) -I. win-resource.rc -O coff -o "$(WIN_DIST)/icon.res"
	$(MINGW_CC) $(CFLAGS) -I"$(SDL3_MINGW_ROOT)/include" main.c controls.c snake_audio.c "$(WIN_DIST)/icon.res" -L"$(SDL3_MINGW_ROOT)/lib" -lSDL3 -lm -o "$(WIN_DIST)/armored-snake.exe" -mwindows
	cp "$(SDL3_MINGW_ROOT)/bin/SDL3.dll" "$(WIN_DIST)/SDL3.dll"
	cp assets/*.rgba "$(WIN_DIST)/assets/"
windows-installer: windows
	makensis -NOCD windows-installer.nsi
.PHONY: windows windows-installer
