.PHONY: build test lint clean patch minor major hotfix

SLN ?= SSO-Auth.sln

build:
	dotnet restore $(SLN)
	dotnet build $(SLN) -c Release --no-restore --warnaserror

test: build
	dotnet test $(SLN) -c Release --no-build --verbosity minimal

lint:
	dotnet format $(SLN) --verify-no-changes

clean:
	dotnet clean $(SLN) -c Release || true
	rm -rf SSO-Auth/bin SSO-Auth/obj tests/SSO-Auth.Tests/bin tests/SSO-Auth.Tests/obj

# Jellyfin plugin versions are 4-part (System.Version in the plugin manifest),
# so build.yaml holds the version and the release tag must be exactly
# v<that version>; .woodpecker/release.yaml fails the build if they diverge.
_CUR := $(shell sed -n 's/^version: *"\([0-9.]*\)".*/\1/p' build.yaml | head -1)
_A   := $(or $(word 1,$(subst ., ,$(_CUR))),0)
_B   := $(or $(word 2,$(subst ., ,$(_CUR))),0)
_C   := $(or $(word 3,$(subst ., ,$(_CUR))),0)
_D   := $(or $(word 4,$(subst ., ,$(_CUR))),0)

define release
	@test -n "$(_CUR)" || { echo "cannot parse version from build.yaml"; exit 1; }
	@test -z "$$(git status --porcelain)" || { echo "working tree is dirty"; exit 1; }
	@sed -i 's|^version: .*|version: "$(1)"|' build.yaml
	@sed -i 's|<AssemblyVersion>[^<]*</AssemblyVersion>|<AssemblyVersion>$(1)</AssemblyVersion>|' SSO-Auth/SSO-Auth.csproj
	@sed -i 's|<FileVersion>[^<]*</FileVersion>|<FileVersion>$(1)</FileVersion>|' SSO-Auth/SSO-Auth.csproj
	@git commit -qam "release $(1)"
	@git tag v$(1)
	@git push origin HEAD v$(1)
	@echo "Released v$(1)"
endef

major:
	$(call release,$(shell expr $(_A) + 1).0.0.0)

minor:
	$(call release,$(_A).$(shell expr $(_B) + 1).0.0)

patch:
	$(call release,$(_A).$(_B).$(shell expr $(_C) + 1).0)

# Fourth component: a rebuild of an existing patch (upstream's 3.5.2.1 shape).
hotfix:
	$(call release,$(_A).$(_B).$(_C).$(shell expr $(_D) + 1))
