SHELL := /bin/bash
HOST := famzheng.com
HOST_USER := fam
APP := write

REMOTE_BIN := /home/$(HOST_USER)/.local/bin/$(APP)
REMOTE_DIST := /home/$(HOST_USER)/.local/share/$(APP)/dist
REMOTE_SYSTEMD := /home/$(HOST_USER)/.config/systemd/user/$(APP).service
REMOTE_ENV := /home/$(HOST_USER)/.config/$(APP)/env
REMOTE_STATE := /home/$(HOST_USER)/.local/state/$(APP)

.PHONY: build build-fe build-be deploy install enable start stop restart status logs k8s-apply k8s-delete dev dev-fe local-test

build: build-be build-fe

build-be:
	@cd ../.. && cargo build --release -p $(APP)

build-fe:
	@cd frontend && (test -d node_modules || npm ci) && npm run build

deploy: build
	@echo "==> ensure remote dirs"
	@ssh $(HOST) 'mkdir -p $(dir $(REMOTE_BIN)) $(REMOTE_DIST) $(dir $(REMOTE_SYSTEMD)) $(dir $(REMOTE_ENV)) $(REMOTE_STATE)'
	@echo "==> ship binary"
	@scp ../../target/release/$(APP) $(HOST):$(REMOTE_BIN)
	@echo "==> ship frontend dist"
	@rsync -a --delete frontend/dist/ $(HOST):$(REMOTE_DIST)/
	@echo "==> ship systemd unit"
	@scp systemd/$(APP).service $(HOST):$(REMOTE_SYSTEMD)
	@ssh $(HOST) 'systemctl --user daemon-reload'
	@echo "==> ensure env file (touch if absent)"
	@ssh $(HOST) '[ -f $(REMOTE_ENV) ] || { echo "WRITE_PASSPHRASE=CHANGE-ME" > $(REMOTE_ENV) && chmod 600 $(REMOTE_ENV) && echo "⚠ created placeholder $(REMOTE_ENV) — edit it then run make restart"; }'
	@$(MAKE) enable start status

install:
	@$(MAKE) deploy

enable:
	@ssh $(HOST) 'systemctl --user enable $(APP).service'

start:
	@ssh $(HOST) 'systemctl --user start $(APP).service'

stop:
	@ssh $(HOST) 'systemctl --user stop $(APP).service'

restart:
	@ssh $(HOST) 'systemctl --user restart $(APP).service'

status:
	@ssh $(HOST) 'systemctl --user --no-pager status $(APP).service | head -20'

logs:
	@ssh $(HOST) 'tail -n 200 -f $(REMOTE_STATE)/$(APP).log'

k8s-apply:
	@kubectl apply -f k8s/all.yaml

k8s-delete:
	@kubectl delete -f k8s/all.yaml

# Local dev (runs both backend and frontend with auto-reload).
# Make a config first: ~/.config/write/env (locally) with WRITE_PASSPHRASE=...
dev:
	@echo "==> backend on :31391"
	@( cd ../.. && cargo run --release -p $(APP) ) & \
	 echo "==> frontend on :5173 (vite)"; \
	 cd frontend && npm run dev

dev-fe:
	@cd frontend && npm run dev

# Local end-to-end test (uses ~/.local/share/write paths locally)
local-test:
	@mkdir -p ~/.local/share/write/docs ~/.local/state/write
	@( cd ../.. && \
	  WRITE_PASSPHRASE=test \
	  WRITE_DIST_DIR=$$PWD/apps/write/frontend/dist \
	  PORT=31391 \
	  cargo run --release -p $(APP) ) &
	@echo "==> backend running; ctrl-c to stop"
