# ENV

PROJECT_DIR ?= $(dir $(abspath $(lastword $(MAKEFILE_LIST))))
BUILD_DIR ?= $(PROJECT_DIR)/build
FORGE_SRC ?= $(PROJECT_DIR)/forge-steel
TARGET ?= forge
SCREEN_HEIGHT ?= 480
RUN_ARGS ?= --project=$(PROJECT_DIR)/project -is=$(SCREEN_HEIGHT) -nmr --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 -DVERSION=\"$(VERSION)\" -DOPENGL_MAJOR_VERSION=3 -DOPENGL_MINOR_VERSION=1
LDLIBS ?= -lm -lGL -lglfw -lasound

# FILES

$(BUILD_DIR)/$(TARGET):
	mkdir -p $(BUILD_DIR)
	$(CC) $(SOURCES) $(CFLAGS) $(LDLIBS) -o $(BUILD_DIR)/$(TARGET)

# ACTIONS

.PHONY: usermod
usermod:
	sudo usermod -a -G adm,dialout,cdrom,sudo,audio,video,plugdev,games,users,input,render,netdev,lpadmin,gpio,i2c,spi $(shell whoami)

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

.PHONY: apt-install
apt-install:
	sudo apt update
	sudo apt install -y weston seatd git libglfw3-dev libgl-dev libasound2-dev libv4l-dev i2c-tools python3-gpiozero python3-evdev python3-luma.oled

.PHONY: disable-cloud-init
disable-cloud-init:
	sudo systemctl disable cloud-init.service
	sudo systemctl mask cloud-init.service
	sudo touch /etc/cloud/cloud-init.disabled

.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: install
install: remove-passwd apt-install disable-cloud-init setup-services

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

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

.PHONY: start-fg
start-fg: $(BUILD_DIR)/$(TARGET)
	@$(BUILD_DIR)/$(TARGET) $(RUN_ARGS) 2>&1 | tee -ai $(PROJECT_DIR)/forge.log 2>&1 > /dev/null

.PHONY: start-bg
start-bg:
	@python3 $(PROJECT_DIR)/__main__.py 2>&1 | tee -ai $(PROJECT_DIR)/python.log 2>&1 > /dev/null &

.PHONY: start
start: start-bg start-fg
