# Makefile for Grokway Server

BINARY_NAME=grokway
INSTALL_DIR=/opt/grokway
SERVICE_NAME=grokway.service
SYSTEMD_DIR=/etc/systemd/system

.PHONY: build clean install uninstall help

help:
	@echo "Available commands:"
	@echo "  make build      - Build the server binary"
	@echo "  make install    - Install the server as a systemd service (requires root)"
	@echo "  make uninstall  - Remove the server and service (requires root)"
	@echo "  make clean      - Clean build artifacts"

build:
	@echo "Building $(BINARY_NAME)..."
	go build -o $(BINARY_NAME) ./cmd/server

clean:
	@echo "Cleaning..."
	rm -f $(BINARY_NAME)

install: build
	@echo "Installing $(BINARY_NAME) to $(INSTALL_DIR)..."
	# Create user if not exists
	id -u grokway &>/dev/null || useradd -r -s /bin/false grokway
	# Create directory
	mkdir -p $(INSTALL_DIR)
	# Copy binary
	cp $(BINARY_NAME) $(INSTALL_DIR)/
	# Copy static assets (maintaining structure needed by code)
	# The code expects ./cmd/server/static relative to CWD
	mkdir -p $(INSTALL_DIR)/cmd/server
	cp -r cmd/server/static $(INSTALL_DIR)/cmd/server/
	# Set permissions
	chown -R grokway:grokway $(INSTALL_DIR)
	chmod +x $(INSTALL_DIR)/$(BINARY_NAME)
	# Install Service
	cp $(SERVICE_NAME) $(SYSTEMD_DIR)/
	# Update paths in service file just in case they were modified
	sed -i 's|WorkingDirectory=.*|WorkingDirectory=$(INSTALL_DIR)|g' $(SYSTEMD_DIR)/$(SERVICE_NAME)
	sed -i 's|ExecStart=.*|ExecStart=$(INSTALL_DIR)/$(BINARY_NAME)|g' $(SYSTEMD_DIR)/$(SERVICE_NAME)
	
	systemctl daemon-reload
	systemctl enable $(SERVICE_NAME)
	systemctl start $(SERVICE_NAME)
	@echo "Installation complete. Service started."
	@echo "Important: Edit $(SYSTEMD_DIR)/$(SERVICE_NAME) to set GROKWAY_TOKEN environment variable if needed."
	@echo "Then run: systemctl daemon-reload && systemctl restart $(SERVICE_NAME)"
	@echo "Check status directly with: systemctl status $(SERVICE_NAME)"

uninstall:
	@echo "Uninstalling $(BINARY_NAME)..."
	systemctl stop $(SERVICE_NAME) || true
	systemctl disable $(SERVICE_NAME) || true
	rm -f $(SYSTEMD_DIR)/$(SERVICE_NAME)
	rm -rf $(INSTALL_DIR)
	# Optional: remove user
	# userdel grokway || true
	systemctl daemon-reload
	@echo "Uninstallation complete."
