# ENV

PROJECT_DIR ?= $(dir $(abspath $(lastword $(MAKEFILE_LIST))))
BUILD_DIR ?= $(PROJECT_DIR)/build
FORGE_SRC ?= $(PROJECT_DIR)/forge-steel
TARGET ?= forge
RUN_ARGS ?= --project=$(PROJECT_DIR)/project --internal-size=576 --auto-save
VERSION ?= invar-$(shell grep -Eo '[0-9]+\.[0-9]+\.[0-9]+' $(FORGE_SRC)/configure.ac)
SOURCES ?= $(FORGE_SRC)/src/*.h $(FORGE_SRC)/src/*.c $(FORGE_SRC)/hashmap.c/hashmap.c $(FORGE_SRC)/log.c/src/log.c
CFLAGS ?= -Ofast -Ofast -march=native -flto -funroll-loops -fprefetch-loop-arrays -fno-exceptions -fopenmp -I$(FORGE_SRC)/include -DGLFW_INCLUDE_NONE -DGLFW_NATIVE_INCLUDE_NONE -DLOG_USE_COLOR -DVERSION=\"$(VERSION)\" -DOPENGL_MAJOR_VERSION=3 -DOPENGL_MINOR_VERSION=1
LDLIBS ?= -lm -lGL -lglfw -lasound

# FILES

test:
	echo $(PROJECT_DIR)

forge-steel/src/main.c:
	$(MAKE) -s submodule-init

forge-steel/hashmap.c/hashmap.c:
	$(MAKE) -s submodule-init

forge-steel/log.c/src/log.c:
	$(MAKE) -s submodule-init

forge-steel/include/linmath.h:
	$(MAKE) -s submodule-init

$(BUILD_DIR)/$(TARGET): forge-steel/src/main.c forge-steel/hashmap.c/hashmap.c forge-steel/log.c/src/log.c forge-steel/include/linmath.h
	mkdir -p $(BUILD_DIR)
	$(CC) $(SOURCES) $(CFLAGS) $(LDLIBS) -o $(BUILD_DIR)/$(TARGET)

# ACTIONS

.PHONY: remove-passwd
remove-passwd:
	sudo passwd -d $(shell whoami)

.PHONY: apt-install
apt-install:
	sudo apt install -y weston seatd kitty libglfw3-dev libgl-dev libasound2-dev libv4l-dev

.PHONY: setup-weston
setup-weston:
	ln -fs $(PROJECT_DIR)/system/weston.ini $(HOME)/.config/weston.ini

.PHONY: setup-rasp-config
setup-rasp-config:
	sudo $(PROJECT_DIR)/line_in_file.sh "include forge-invar.txt" "/boot/firmware/config.txt"
	sudo $(PROJECT_DIR)/line_in_file.sh "vc4.tv_norm=PAL" "/boot/firmware/cmdline.txt" "vc4.tv_norm"
	sudo cp -f $(PROJECT_DIR)/system/config.ini /boot/firmware/forge-invar.txt

.PHONY: setup-services
setup-services:
	sudo ln -fs $(PROJECT_DIR)/system/getty@tty1.service /etc/systemd/system/getty@tty1.service
	sudo systemctl daemon-reload
	sudo systemctl enable getty@tty1.service seatd.service

.PHONY: setup-user-services
setup-user-services:
	sudo ln -fs $(PROJECT_DIR)/system/weston.service /etc/systemd/user/weston.service
	sudo ln -fs $(PROJECT_DIR)/system/weston.socket /etc/systemd/user/weston.socket
	systemctl --user daemon-reload
	systemctl --user enable weston

.PHONY: setup-bashrc
setup-bashrc:
	$(PROJECT_DIR)/line_in_file.sh "make -C $(PROJECT_DIR) start-weston" "$(HOME)/.bashrc"

.PHONY: install
install: remove-passwd apt-install setup-weston setup-rasp-config setup-services setup-bashrc

.PHONY: clean
clean:
	$(RM) -r $(BUILD_DIR)

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

.PHONY: run
run: $(BUILD_DIR)/$(TARGET)
	# $(BUILD_DIR)/$(TARGET) $(RUN_ARGS)
	$(PROJECT_DIR)/delay.sh

.PHONY: submodule-init
submodule-init:
	git submodule update --init --recursive

.PHONY: start-weston
start-weston:
	/usr/bin/weston --shell=kiosk-shell.so --xwayland -- kitty --hold make -C $(PROJECT_DIR) run
