SHELL := /bin/bash

PNPM ?= pnpm
GO ?= go
CONTAINER_REG ?= repo.ssp-itinfra.com/admin
IMAGE_NAME ?= shooting-event
ARCH ?= amd64
BUILD_DATE ?= $(shell date -u +"%Y-%m-%dT%H:%M:%SZ")
BUILD_VERSION ?= $(shell git describe --tags --always --dirty)

.PHONY: install dev dev-backend dev-frontend build build-frontend build-backend docker-build docker-run clean

install:
	cd frontend && $(PNPM) install
	cd backend && $(GO) mod tidy

dev-backend:
	cd backend && $(GO) run .

dev-frontend:
	cd frontend && $(PNPM) dev

dev:
	@set -euo pipefail; \
	trap 'kill 0' INT TERM EXIT; \
	$(MAKE) dev-backend & \
	$(MAKE) dev-frontend & \
	wait

build-frontend:
	cd frontend && $(PNPM) build

build-backend:
	mkdir -p bin
	cd backend && $(GO) build -o ../bin/shooting-event .

build: build-frontend
	rm -rf backend/web
	mkdir -p backend/web
	cp -R frontend/dist/. backend/web/
	$(MAKE) build-backend

docker-build:
	docker buildx build --load --platform=linux/$(ARCH) -t $(CONTAINER_REG)/$(IMAGE_NAME):$(ARCH) .
	docker tag $(CONTAINER_REG)/$(IMAGE_NAME):$(ARCH) $(CONTAINER_REG)/$(IMAGE_NAME):$(ARCH)-latest
	docker tag $(CONTAINER_REG)/$(IMAGE_NAME):$(ARCH) $(CONTAINER_REG)/$(IMAGE_NAME):$(ARCH)-$(BUILD_VERSION)
	docker push $(CONTAINER_REG)/$(IMAGE_NAME):$(ARCH)
	docker push $(CONTAINER_REG)/$(IMAGE_NAME):$(ARCH)-latest
	docker push $(CONTAINER_REG)/$(IMAGE_NAME):$(ARCH)-$(BUILD_VERSION)

docker-run:
	mkdir -p data
	docker run --rm -p 8080:8080 -v $(PWD)/data:/app/data $(CONTAINER_REG)/$(IMAGE_NAME):$(ARCH)

release:
	$(MAKE) docker-build
	
clean:
	rm -rf bin frontend/dist backend/web
