.PHONY: all clean norm author author-stop author-restart help

VENV := .venv
PY := $(VENV)/bin/python
PIP := $(VENV)/bin/pip
PERM_DIR := /home/zaine/master-folder/projects/scripts/bash-scripts

AUTHOR_PORT := 8765
AUTHOR_PID := /home/zaine/logs/authoring-server.pid
AUTHOR_LOG := /home/zaine/logs/authoring-server.log

all: set-perms clean-output build search clean-venv author-restart

build:
	@echo "Building project..."
	emacs -Q --script build-site.el

set-perms:
	@echo "Setting permissions for output directory..."
	cd $(PERM_DIR) && sudo ./master-perms.sh

search: $(VENV)
	@echo "Generating search index"
	$(PY) search-index-json.py

$(VENV):
	@echo "Generating virtual environment"
	python3 -m venv $(VENV)
	$(PIP) install -r requirements.txt

clean-output:
	@echo "Cleaning output directory..."
	rm -rf output/

clean-venv:
	@echo "Cleaning virtual environment..."
	rm -rf $(VENV)

norm:
	@echo "sorting out the backups..."
	find . -path ./backups -prune -o -type f -name '*~' -exec mv {} backups/ \;

author:
	@echo "Starting local authoring UI in foreground..."
	python3 authoring_server.py

author-stop:
	@echo "Stopping existing authoring UI if running..."
	@mkdir -p /home/zaine/logs
	@if [ -f "$(AUTHOR_PID)" ]; then \
		PID=$$(cat "$(AUTHOR_PID)"); \
		if kill -0 $$PID 2>/dev/null; then \
			echo "Killing PID $$PID"; \
			kill $$PID || true; \
			sleep 1; \
		fi; \
		rm -f "$(AUTHOR_PID)"; \
	fi
	@fuser -k $(AUTHOR_PORT)/tcp 2>/dev/null || true

author-restart: author-stop
	@echo "Starting authoring UI on port $(AUTHOR_PORT)..."
	@mkdir -p /home/zaine/logs
	@nohup python3 authoring_server.py > "$(AUTHOR_LOG)" 2>&1 & echo $$! > "$(AUTHOR_PID)"
	@echo "Waiting for authoring UI to respond..."
	@for i in 1 2 3 4 5 6 7 8 9 10; do \
		if curl -fsS http://127.0.0.1:$(AUTHOR_PORT)/ >/dev/null; then \
			echo "Authoring UI is running on http://127.0.0.1:$(AUTHOR_PORT)/"; \
			exit 0; \
		fi; \
		sleep 1; \
	done; \
	echo "Authoring UI failed to start. Last logs:"; \
	tail -n 40 "$(AUTHOR_LOG)" || true; \
	exit 1

help:
	@echo "Available targets:"
	@echo "  make                 - Full rebuild and restart authoring UI"
	@echo "  make build           - Rebuild the output directory"
	@echo "  make set-perms       - Set permissions for output directory"
	@echo "  make clean-output    - Remove output directory"
	@echo "  make clean-venv      - Remove venv directory"
	@echo "  make norm            - Move backup files"
	@echo "  make author          - Start the local authoring UI in foreground"
	@echo "  make author-stop     - Stop the authoring UI"
	@echo "  make author-restart  - Restart the authoring UI in background"
	@echo "  make search          - Create the search index"
	@echo "  make help            - Show this help message"
