GO ?= go
PNPM ?= corepack pnpm
GORELEASER ?= goreleaser
VERSION ?= v0.0.0
REVISION ?= $(shell git rev-parse HEAD)
BIN ?= customer-service
override OFFLINE := sh ./scripts/run-network-isolated.sh env COREPACK_ENABLE_NETWORK=0
GO_RELEASE_FLAGS := -mod=vendor -trimpath -buildvcs=false
GO_RELEASE_LDFLAGS := -s -w -buildid= -X main.buildString=$(VERSION)-$(REVISION) -X main.versionString=$(VERSION) -X github.com/abhinavxd/libredesk/internal/version.Version=$(VERSION)

.DEFAULT_GOAL := build

.PHONY: source-offer verify-inputs frontend-build release-tools build-backend stuff build test snapshot private-deploy-check

source-offer:
	@sh ./scripts/prepare-agpl-source-offer.sh '$(REVISION)'
	@sh ./scripts/verify-agpl-source-offer.sh '$(REVISION)'

verify-inputs:
	@$(OFFLINE) env GOPROXY=off GOSUMDB=off GOTOOLCHAIN=local GOFLAGS=-mod=vendor sh ./scripts/verify-release-inputs.sh

frontend-build:
	@$(OFFLINE) env npm_config_offline=true $(PNPM) --dir frontend install --frozen-lockfile --offline --ignore-scripts
	@$(OFFLINE) env npm_config_offline=true $(PNPM) --dir frontend build:main
	@$(OFFLINE) env npm_config_offline=true $(PNPM) --dir frontend build:widget
	@$(MAKE) verify-inputs

release-tools:
	@$(OFFLINE) env GO='$(GO)' GOPROXY=off GOSUMDB=off GOTOOLCHAIN=local GOFLAGS=-mod=vendor sh ./scripts/prepare-release-tools.sh

build-backend: release-tools
	@$(OFFLINE) env CGO_ENABLED=0 GOPROXY=off GOSUMDB=off GOTOOLCHAIN=local GOFLAGS=-mod=vendor \
		$(GO) build $(GO_RELEASE_FLAGS) -ldflags='$(GO_RELEASE_LDFLAGS)' -o $(BIN) ./cmd

stuff: source-offer build-backend
	@$(OFFLINE) sh ./scripts/release-stuff.sh '$(BIN)'

build: frontend-build stuff
	@printf 'built %s at revision %s\n' '$(BIN)' '$(REVISION)'

test:
	@sh ./scripts/test-offline-build-chain.sh
	@sh ./scripts/test-release-supply-chain-evidence.sh
	@sh ./scripts/test-private-image-supply-chain.sh
	@sh ./scripts/test-private-redis-config.sh
	@sh ./scripts/test-production-cutover-state.sh
	@sh ./scripts/test-production-cutover-evidence.sh
	@sh ./scripts/test-redis-aof-volume.sh
	@sh ./scripts/test-postgres-row-count-evidence.sh
	@python3 ./scripts/test-prepare-production-secrets.py
	@$(OFFLINE) env GOPROXY=off GOSUMDB=off GOTOOLCHAIN=local GOFLAGS=-mod=vendor $(GO) test -count=1 ./...
	@$(OFFLINE) env npm_config_offline=true $(PNPM) --dir frontend test:run

snapshot:
	@$(OFFLINE) env GOPROXY=off GOSUMDB=off GOTOOLCHAIN=local GOFLAGS=-mod=vendor $(GORELEASER) release --snapshot --clean

private-deploy-check:
	@sh ./scripts/verify-private-deployment.sh
