# NextReceipt — AI-Powered Receipt Saver
# Makefile for build, install, and deployment

BINARY  = app
SERVICE = nextreceipt
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 NextReceipt..."
	cp $(BINARY) /usr/local/bin/$(BINARY)
	@if [ ! -f /etc/$(SERVICE)/.env ]; then \
		mkdir -p /etc/$(SERVICE); \
		cp .env.example /etc/$(SERVICE)/.env; \
		echo "==> Created /etc/$(SERVICE)/.env — edit it with your credentials"; \
	fi
	@if [ ! -f /etc/systemd/system/$(SERVICE).service ]; then \
		cp contrib/$(SERVICE).service /etc/systemd/system/; \
		systemctl daemon-reload; \
		systemctl enable $(SERVICE); \
		echo "==> Systemd service installed"; \
	fi
	@echo "==> Run 'systemctl start $(SERVICE)' to start"
	@echo "==> Run 'systemctl status $(SERVICE)' to check status"

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

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

run:
	./$(BINARY)

start:
	systemctl start $(SERVICE)

stop:
	systemctl stop $(SERVICE)

restart:
	systemctl restart $(SERVICE)

logs:
	journalctl -u $(SERVICE) -f

status:
	systemctl status $(SERVICE)

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

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