TARGET ?= forge
INSTALL_DIR ?= $(HOME)/.local/bin
TEST_ARGS ?= --video-in=/dev/video0 --video-in=/dev/video1 --video-in=/dev/video2 --video-in=/dev/video3 --video-in=/dev/video4 --video-in=/dev/video5 --video-in=/dev/video6 --video-in=/dev/video7 --video-in=/dev/video8 --video-in=/dev/video9
SHELL := /bin/bash

.PHONY: build
clean:
	@rm -rf build

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

.PHONY: run
run: build
	./build/$(TARGET) $(TEST_ARGS) --monitor-only --internal-size=480 --video-size=240 --hot-reload

.PHONY: demo
demo: build
	./build/$(TARGET) $(TEST_ARGS) --demo

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

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

.PHONY: clean-release
clean-release:
	@rm -rf \
		autom4te.cache \
		aclocal.m4 \
		compile \
		config.* \
		configure \
		configure~ \
		depcomp \
		**/.deps \
		$(TARGET) \
		$(TARGET)-*.tar.gz \
		$(TARGET)-*.pkg.tar.zst \
		install-sh \
		Makefile \
		Makefile.in \
		missing \
		src/.* \
		src/*.o

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

.PHONY: release-%
release-%: clean clean-release
	git pull origin master
	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-$*"
	git tag steel-$* -m "forge steel-$*"
	@echo "Push release: git push origin master --tags"
	@echo "Rollback release: git reset HEAD~1 --hard && git tag -d steel-$*"


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

