BINARY=cpone-dashboard
SERVER=one@devcpone.aplikasi.web.id
DEPLOY_DIR=/home/one/project/cpone-dashboard
GO ?= go

.PHONY: run build deploy local stop start restart

run:
	$(GO) run .

local:
	GOCACHE=/tmp/cpone-gocache $(GO) run .

start:
	@if lsof -nP -iTCP:3307 -sTCP:LISTEN >/dev/null 2>&1; then \
		echo "tunnel 3307 already running"; \
	else \
		echo "starting tunnel 3307 -> devcpone"; \
		ssh -f -N -L 3307:127.0.0.1:3306 one@devcpone.aplikasi.web.id; \
	fi
	@echo "starting dashboard on http://localhost:8080/dashboard"
	GOCACHE=/tmp/cpone-gocache $(GO) run .

stop:
	@pids="$$(lsof -t -iTCP:8080 -sTCP:LISTEN 2>/dev/null) $$(lsof -t -iTCP:3307 -sTCP:LISTEN 2>/dev/null)"; \
	if [ -z "$$pids" ]; then \
		echo "nothing to stop"; \
	else \
		echo "$$pids" | tr ' ' '\n' | sort -u | xargs kill; \
		echo "stopped local dashboard and tunnel"; \
	fi

restart: stop start

build:
	GOOS=linux GOARCH=amd64 $(GO) build -o $(BINARY)-linux .

deploy: build
	scp $(BINARY)-linux $(SERVER):$(DEPLOY_DIR)/$(BINARY)
	ssh $(SERVER) "chmod +x $(DEPLOY_DIR)/$(BINARY) && systemctl --user restart cpone-dashboard"
	@echo "deployed → https://devcpone.aplikasi.web.id/cpone-dashboard"

logs:
	ssh $(SERVER) "journalctl --user -u cpone-dashboard -f --no-pager"

status:
	ssh $(SERVER) "systemctl --user status cpone-dashboard --no-pager"
