# OPLabs Mixer Backend — install / uninstall / restart / status

VENV := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))venv
SERVICE := oplabs-mixer-backend.service
SERVICE_PATH := /etc/systemd/system/$(SERVICE)
UVICORN := $(VENV)/bin/uvicorn
APP_DIR := $(dir $(realpath $(lastword $(MAKEFILE_LIST))))
DAEMON_DIR := $(APP_DIR)../../oplabs-mixer-daemon

.PHONY: install uninstall restart status start stop logs deps deps-daemon dev

# Install systemd service and start it
install: daemon-service-install
	sudo cp $(SERVICE) $(SERVICE_PATH)
	sudo systemctl daemon-reload
	sudo systemctl enable $(SERVICE)
	sudo systemctl restart $(SERVICE)
	@echo "=== Service status ==="
	sudo systemctl status --no-pager $(SERVICE)

# Install the mixer daemon service (dependency for backend)
daemon-service-install:
	@if [ -f $(DAEMON_DIR)/Makefile ]; then \
		echo "=== Installing mixer daemon service ==="; \
		$(MAKE) -C $(DAEMON_DIR) install; \
	else \
		echo "WARNING: mixer-daemon repo not found at $(DAEMON_DIR)"; \
		echo "Install the daemon service manually from its repo."; \
	fi
	sudo cp $(SERVICE) $(SERVICE_PATH)
	sudo systemctl daemon-reload
	sudo systemctl enable $(SERVICE)
	sudo systemctl restart $(SERVICE)
	@echo "=== Service status ==="
	sudo systemctl status --no-pager $(SERVICE)

# Remove systemd service
uninstall:
	sudo systemctl stop $(SERVICE) || true
	sudo systemctl disable $(SERVICE) || true
	sudo rm -f $(SERVICE_PATH)
	sudo systemctl daemon-reload

restart:
	sudo systemctl restart $(SERVICE)
	sudo systemctl status --no-pager $(SERVICE)

status:
	sudo systemctl status --no-pager $(SERVICE)

start:
	sudo systemctl start $(SERVICE)

stop:
	sudo systemctl stop $(SERVICE)

logs:
	sudo journalctl -u $(SERVICE) -n 100 -f

# Install Python deps
deps:
	$(VENV)/bin/pip install -r requirements.txt

# Run dev server (no systemd, hot-reload)
dev:
	$(UVICORN) app:app --host 0.0.0.0 --port 8081 --reload --log-level info
