# for development, db in cwd
export DATABASE_PATH := ./storage.sqlite

VERSION := $(shell git rev-parse --short HEAD)
BUILDARCH := $(shell uname -m)
BUILDTIMETAG := $(shell date -u '+%Y%m%d%H%M%S')

FN := server
IMAGENAME := sneak/orangesite

GOLDFLAGS += -X main.Version=$(VERSION)
GOLDFLAGS += -X main.Buildarch=$(BUILDARCH)
GOFLAGS := -ldflags "$(GOLDFLAGS)"

.PHONY: default run debug build clean \
	test lint fmt fmt-check check docker hooks \
	docker-dist docker-push

default: run

# --- development ---------------------------------------------------------

run: build
	./$(FN)

debug: build
	GOTRACEBACK=all DEBUG=1 ./$(FN)

build:
	go build -o $(FN) $(GOFLAGS) ./cmd/$(FN)

clean:
	-rm -f ./$(FN)

# --- required policy targets ---------------------------------------------

# run tests quietly; on failure, rerun verbosely for diagnostics
test:
	@go test -timeout 30s ./... || \
		{ echo "--- Rerunning with -v for details ---"; \
		  go test -timeout 30s -v ./...; exit 1; }

lint:
	golangci-lint run ./...

fmt:
	gofmt -s -w .

fmt-check:
	@out="$$(gofmt -s -l .)"; \
	if [ -n "$$out" ]; then \
		echo "gofmt needed on:"; echo "$$out"; exit 1; \
	fi

# check must not modify any files in the repo
check: fmt-check lint test

docker:
	docker build -t $(IMAGENAME) .

hooks:
	@printf '#!/bin/sh\nset -e\n' > .git/hooks/pre-commit
	@printf 'go mod tidy\ngofmt -s -w .\n' >> .git/hooks/pre-commit
	@printf 'git diff --exit-code -- go.mod go.sum || { echo "go mod tidy changed files; please stage and retry"; exit 1; }\n' >> .git/hooks/pre-commit
	@printf 'make check\n' >> .git/hooks/pre-commit
	@chmod +x .git/hooks/pre-commit
	@echo "installed .git/hooks/pre-commit"

# --- image distribution --------------------------------------------------

docker-dist: docker
	docker tag $(IMAGENAME) $(IMAGENAME):$(VERSION)
	docker tag $(IMAGENAME) $(IMAGENAME):$(BUILDTIMETAG)

docker-push: docker-dist
	docker push $(IMAGENAME):$(VERSION)
	docker push $(IMAGENAME):$(BUILDTIMETAG)
	docker push $(IMAGENAME):latest
