# NextExpense — AI-Powered Expense Tracker
# Makefile for build, install, and deployment

BINARY  = app
OUTDIR  = dist
VERSION = v1.0.0
LDFLAGS = -s -w

.PHONY: all build clean install uninstall run stop restart logs

all: build

# -------------------------------------------------------------------
# Build
# -------------------------------------------------------------------

build:
	go build -ldflags="$(LDFLAGS)" -o $(BINARY) .

build-linux-amd64:
	GOOS=linux GOARCH=amd64 go build -ldflags="$(LDFLAGS)" -o $(OUTDIR)/$(BINARY)-linux-amd64 .

build-linux-arm64:
	GOOS=linux GOARCH=arm64 CGO_ENABLED=1 CC=aarch64-linux-gnu-gcc go build -ldflags="$(LDFLAGS)" -o $(OUTDIR)/$(BINARY)-linux-arm64 .

build-all: build-linux-amd64 build-linux-arm64

# -------------------------------------------------------------------
# Install (systemd service)
# -------------------------------------------------------------------

install: build
	@echo "==> Installing NextExpense..."
	cp $(BINARY) /usr/local/bin/$(BINARY)
	@if [ ! -f /etc/$(BINARY)/.env ]; then \
		mkdir -p /etc/$(BINARY); \
		cp .env.example /etc/$(BINARY)/.env; \
		echo "==> Created /etc/$(BINARY)/.env — edit it with your credentials"; \
	fi
	@if [ ! -f /etc/systemd/system/$(BINARY).service ]; then \
		cp contrib/$(BINARY).service /etc/systemd/system/; \
		systemctl daemon-reload; \
		systemctl enable $(BINARY); \
		echo "==> Systemd service installed"; \
	fi
	@echo "==> Run 'systemctl start $(BINARY)' to start"
	@echo "==> Run 'systemctl status $(BINARY)' to check status"

uninstall:
	-systemctl stop $(BINARY) 2>/dev/null
	-systemctl disable $(BINARY) 2>/dev/null
	-rm -f /etc/systemd/system/$(BINARY).service
	-systemctl daemon-reload
	-rm -f /usr/local/bin/$(BINARY)
	@echo "==> NextExpense uninstalled"

# -------------------------------------------------------------------
# Service management
# -------------------------------------------------------------------

run:
	./$(BINARY)

start:
	systemctl start $(BINARY)

stop:
	systemctl stop $(BINARY)

restart:
	systemctl restart $(BINARY)

logs:
	journalctl -u $(BINARY) -f

status:
	systemctl status $(BINARY)

# -------------------------------------------------------------------
# Clean
# -------------------------------------------------------------------

clean:
	rm -f $(BINARY)
	rm -rf $(OUTDIR)
