BINARY := dealspace
BUILD_DIR := build
SHANNON := root@82.24.174.112
DEPLOY_PATH := /opt/dealspace
REMOTE_MIG := /opt/dealspace/migrations

.PHONY: build build-linux run test clean deploy install-service logs ssh health

build:
	@mkdir -p $(BUILD_DIR)
	@# Copy website into cmd/server for go:embed
	@rm -rf cmd/server/website
	@cp -r website cmd/server/website
	go build -o $(BUILD_DIR)/$(BINARY) ./cmd/server
	@rm -rf cmd/server/website
	@echo "Built $(BUILD_DIR)/$(BINARY)"

build-linux:
	@mkdir -p $(BUILD_DIR)
	@rm -rf cmd/server/website
	@cp -r website cmd/server/website
	CGO_ENABLED=1 GOOS=linux GOARCH=amd64 PATH=$(PATH):/usr/local/go/bin go build -tags fts5 -o $(BUILD_DIR)/$(BINARY)-linux ./cmd/server
	@rm -rf cmd/server/website
	@echo "Built $(BUILD_DIR)/$(BINARY)-linux"

run: build
	$(BUILD_DIR)/$(BINARY)

test:
	CGO_ENABLED=1 PATH=$(PATH):/usr/local/go/bin go test -tags fts5 ./... -v

clean:
	rm -rf $(BUILD_DIR)
	rm -rf cmd/server/website

deploy: clean build-linux
	ssh $(SHANNON) "systemctl stop dealspace || true"
	scp $(BUILD_DIR)/$(BINARY)-linux $(SHANNON):$(DEPLOY_PATH)/bin/dealspace
	scp migrations/*.sql $(SHANNON):$(REMOTE_MIG)/
	scp -r portal $(SHANNON):$(DEPLOY_PATH)/
	ssh $(SHANNON) "chmod +x $(DEPLOY_PATH)/bin/dealspace && systemctl start dealspace && sleep 2 && curl -s http://localhost:8080/health"
	@echo "Deployed ✓"

install-service:
	scp deploy/dealspace.service $(SHANNON):/etc/systemd/system/
	scp deploy/backup.sh $(SHANNON):$(DEPLOY_PATH)/
	scp deploy/healthcheck.sh $(SHANNON):$(DEPLOY_PATH)/
	ssh $(SHANNON) "chmod +x $(DEPLOY_PATH)/backup.sh $(DEPLOY_PATH)/healthcheck.sh && systemctl daemon-reload && systemctl enable dealspace"
	@echo "Service installed ✓"

logs:
	ssh $(SHANNON) "journalctl -u dealspace -f --no-pager"

ssh:
	ssh $(SHANNON)

health:
	curl -s https://muskepo.com/health | python3 -m json.tool
