SHELL := /bin/bash
.SHELLFLAGS := -eu -o pipefail -c
.DEFAULT_GOAL := help
DEPLOY_HOST ?= fzc
APP ?= cube
APPS := cube articulate karaoke notes simpleasm video2slides webgl werewolf llm-proxy
NAMESPACE = $(if $(filter llm-proxy,$(APP)),llm-proxy,cube-$(APP))
RELEASE_TAG := $(shell git rev-parse --short=12 HEAD)-$(shell date -u +%Y%m%d%H%M%S)
IMAGE ?= cube-local-$(APP):$(RELEASE_TAG)
.PHONY: help guard build deploy deploy-write
help:
	@echo 'make deploy APP=<$(APPS)>; make deploy-write'
guard:
	@case ' $(APPS) ' in *' $(APP) '*) ;; *) echo 'Unknown/decommissioned app'; exit 1;; esac
	@test -z "$$(git status --porcelain)" || { echo 'Review/commit source changes first'; exit 1; }
build: guard
	cargo test -p $(APP)
	CC_x86_64_unknown_linux_musl=musl-gcc cargo build --release --target x86_64-unknown-linux-musl -p $(APP)
	@if [ -f apps/$(APP)/frontend/package.json ]; then cd apps/$(APP)/frontend && npm ci && npm run build; fi
	docker build -f apps/$(APP)/Dockerfile -t $(IMAGE) .
deploy: guard
	$(MAKE) build APP=$(APP) IMAGE=$(IMAGE)
	docker save $(IMAGE) | ssh $(DEPLOY_HOST) 'sudo k3s ctr -n k8s.io images import -'
	python3 scripts/release_remote.py --host $(DEPLOY_HOST) --namespace $(NAMESPACE) --deployment $(APP) --container $(APP) --image $(IMAGE)
deploy-write:
	$(MAKE) -C apps/write deploy HOST=$(DEPLOY_HOST)
