TARGET ?= forge
INSTALL_DIR ?= $(HOME)/.local/bin
RUN_ARGS ?= --help
SHELL := /bin/bash

.PHONY: build
clean:
	@rm -rf build

build/$(TARGET):
	@mkdir -p build
	gcc \
		src/*.h src/*.c \
		-Iinclude \
		hashmap.c/hashmap.c \
		log.c/src/log.c \
		-lm -lGL -lglfw -lasound \
		-Wall -Wextra \
		-Wno-format-truncation \
		-DGLFW_INCLUDE_NONE \
		-DGLFW_EXPOSE_NATIVE_EGL \
		-DGLFW_NATIVE_INCLUDE_NONE \
		-DLOG_USE_COLOR \
		-DVIDEO_IN \
		-o build/$(TARGET) \
		-g -Og

.PHONY: build
build: build/$(TARGET)

.PHONY: build-no-video
build-no-video:
	@mkdir -p build
	gcc \
		src/*.h src/*.c \
		-Iinclude \
		hashmap.c/hashmap.c \
		log.c/src/log.c \
		-lm -lGL -lglfw -lasound \
		-Wall -Wextra \
		-Wno-format-truncation \
		-Wno-unused-parameter \
		-DGLFW_INCLUDE_NONE \
		-DGLFW_NATIVE_INCLUDE_NONE \
		-DLOG_USE_COLOR \
		-o build/$(TARGET) \
		-g -Og

.PHONY: format
format:
	clang-format -i src/*

.PHONY: run
run: build/$(TARGET)
	./build/$(TARGET) $(RUN_ARGS)

.PHONY: sample
sample: build/$(TARGET)
	./build/$(TARGET) --project=sample $(RUN_ARGS)

.PHONY: valgrind
valgrind: build/$(TARGET)
	valgrind \
		--show-realloc-size-zero=no \
		--undef-value-errors=no \
		./build/$(TARGET) $(RUN_ARGS)

.PHONY: full-clean
full-clean:
	git clean -f -x
	rm -rf */*/.deps
	rm -rf */.deps

.PHONY: test-release
test-release: clean full-clean
	aclocal
	autoconf
	automake --add-missing
	./configure
	make distcheck
	mkdir -p build
	cp $(TARGET)-steel-*.tar.gz build/

.PHONY: release-%
release-%: clean full-clean
	git pull origin main
	sed -i -E "s/[0-9]+\\.[0-9]+\\.[0-9]+/$*/g" configure.ac
	aclocal
	autoconf
	automake --add-missing
	./configure
	make distcheck
	mkdir -p build
	cp "$(TARGET)-steel-$*.tar.gz" build/
	sed -i -E "s/pkgver=[0-9]+\\.[0-9]+\\.[0-9]+/pkgver=$*/g" PKGBUILD
	sha256sum build/forge-steel-$*.tar.gz | cut -d' ' -f1 | xargs -I{} sed -i -E "s/sha256sums=\\('.*'\\)/sha256sums=\\('{}'\\)/g" PKGBUILD
	git add configure.ac PKGBUILD
	git commit -am "forge (steel) v$*"
	git tag v$* -m "FORGE steel-$*"
	@echo "Push release: git push origin main --tags"
	@echo "Rollback release: git reset HEAD~1 --hard && git tag -d v$*"


.PHONY: release-arch
release-arch: clean
	mkdir -p build
	cp PKGBUILD build
	cd build && makepkg
