PY ?= python3
VENV ?= .venv
SERVICE_NAME ?= music-light.service
SYSTEMD_USER_DIR ?= $(HOME)/.config/systemd/user
SERVICE_FILE := $(SYSTEMD_USER_DIR)/$(SERVICE_NAME)
CONFIG_DIR ?= $(HOME)/.config/music-light
ENV_FILE ?= $(CONFIG_DIR)/env

.PHONY: venv deps run service-env install-service uninstall-service start-service stop-service restart-service status-service logs-service

venv:
	$(PY) -m venv $(VENV)
	$(VENV)/bin/python -m pip install -U pip

deps: venv
	$(VENV)/bin/pip install -r requirements.txt

run: deps
	$(VENV)/bin/python luz-musica.py

service-env:
	install -d $(CONFIG_DIR)
	test -f $(ENV_FILE) || install -m 600 music-light.env.example $(ENV_FILE)

install-service: deps service-env
	install -d $(SYSTEMD_USER_DIR)
	printf '%s\n' '[Unit]' 'Description=Music Light album-art color sync' 'After=graphical-session.target' 'Wants=graphical-session.target' '' '[Service]' 'Type=simple' 'WorkingDirectory=$(CURDIR)' 'Environment=PYTHONUNBUFFERED=1' 'Environment=PLAYERCTL_BIN=/usr/bin/playerctl' 'EnvironmentFile=-%h/.config/music-light/env' 'ExecStart=$(abspath $(VENV))/bin/python $(CURDIR)/luz-musica.py' 'Restart=always' 'RestartSec=5' '' '[Install]' 'WantedBy=default.target' > $(SERVICE_FILE)
	systemctl --user daemon-reload
	systemctl --user enable --now $(SERVICE_NAME)

uninstall-service:
	systemctl --user disable --now $(SERVICE_NAME) || true
	rm -f $(SERVICE_FILE)
	systemctl --user daemon-reload

start-service:
	systemctl --user start $(SERVICE_NAME)

stop-service:
	systemctl --user stop $(SERVICE_NAME)

restart-service:
	systemctl --user restart $(SERVICE_NAME)

status-service:
	systemctl --user status $(SERVICE_NAME)

logs-service:
	journalctl --user -u $(SERVICE_NAME) -f
