BINARY=gear

SHADERC=sokol-shdc

CFLAGS=-I. -Iinclude -Wall -Wextra -Werror -Wno-header-guard -Wno-comment -g
LDFLAGS=-g
SHADER_FLAGS=--slang glsl430:hlsl5:metal_macos

C_FILES=$(shell find -L src -type f -name '*.c')
C_OBJ=$(C_FILES:.c=.o)

SHADER_FILES=$(shell find -L * -type f -name '*.glsl')
SHADER_OBJ=$(SHADER_FILES:.glsl=.glsl.h)

RESOURCES_DIR=res
RESOURCES_C=$(RESOURCES_DIR)/res.c
RESOURCES_OBJ=$(RESOURCES_DIR)/res.o
RESOURCES_H=include/gear/resources.h
RESOURCE_FILES=$(shell find -L res -type f -not -name '*.o' -not -name '*.c')

ifeq ($(CC), gcc)
	CFLAGS += -Wno-use-after-free
endif

ifeq ($(OS), Windows_NT)
	CFLAGS += -DSOKOL_D3D11 -D_CRT_SECURE_NO_WARNINGS
	BINARY := $(BINARY).exe
else
	UNAME_S := $(shell uname -s)
	ifeq ($(UNAME_S), Linux)
		CFLAGS += -DSOKOL_GLCORE
		LDFLAGS += $(shell pkg-config --libs x11 xi xcursor gl) -ldl -pthread -lm -lasound
	endif
	ifeq ($(UNAME_S), Darwin)
		CFLAGS += -DSOKOL_METAL
		LDFLAGS += -framework Cocoa -framework QuartzCore -framework Metal -framework MetalKit -framework AudioToolbox

		OBJC_FILES=$(shell find -L * -type f -name '*.m')
		OBJC_OBJ=$(OBJC_FILES:.m=.o)
	endif
endif

.PHONY: shaders resources

$(BINARY): shaders resources $(C_OBJ) $(OBJC_OBJ)
	$(CC) $(C_OBJ) $(OBJC_OBJ) $(RESOURCES_OBJ) $(LDFLAGS) -o $(BINARY)

shaders: $(SHADER_OBJ)
	@echo Shaders compiled

resources:
	@echo "// Generated resource file" > res/res.c
	$(foreach res, $(RESOURCE_FILES), xxd -i $(res) >> $(RESOURCES_C);)
	$(CC) -o $(RESOURCES_OBJ) -c $(RESOURCES_C)

	@echo "#ifndef __G_RESOURCES_H__" > $(RESOURCES_H)
	@echo "#define __G_RESOURCES_H__" >> $(RESOURCES_H)
	@nm -g -j $(RESOURCES_OBJ) | \
	awk '{ if($$0 ~ /len$$/) { print "extern int " substr($$0, 2) ";" } else { print "extern char " substr($$0, 2) "[];" } }' >> $(RESOURCES_H)
	@echo "#endif" >> $(RESOURCES_H)
	@echo Resources compiled

%.glsl.h: %.glsl
	$(SHADERC) --input $< --output $@ $(SHADER_FLAGS)

%.o: %.c
	$(CC) -o $@ -c $< $(CFLAGS)

%.o: %.m
	$(CC) -o $@ -c $< $(OBJC_FLAGS) $(CFLAGS)

run: $(BINARY)
	./$(BINARY)

bear: clean
	bear -- $(MAKE) $(BINARY)

clean:
	rm -rf $(C_OBJ) $(OBJC_OBJ) $(SHADER_OBJ) $(RESOURCES_OBJ) $(RESOURCES_H) $(BINARY)
