VERSION  ?= 5.1.1
REVISION ?= 1

NAME  := gitea-runner-$(VERSION)-linux-amd64
BASE  := https://gitea.com/gitea/runner/releases/download/v$(VERSION)
PKG   := gitea-runner_$(VERSION)-$(REVISION)_amd64
STAGE := build/$(PKG)
BIN   := cache/$(NAME)
SUMS  := cache/checksums-$(VERSION).txt

.PHONY: deb clean
deb: build/$(PKG).deb

$(SUMS):
	mkdir -p cache
	curl -fsSL -o $@ $(BASE)/checksums.txt

$(BIN): $(SUMS)
	curl -fsSL -o $@ $(BASE)/$(NAME)
	cd cache && grep -E '[ *]$(NAME)$$' checksums-$(VERSION).txt | sha256sum -c - \
	  || { rm -f $(NAME); echo "Checksum verification failed" >&2; exit 1; }

build/$(PKG).deb: $(BIN) $(shell find pkg -type f)
	rm -rf $(STAGE)
	mkdir -p $(STAGE)
	cp -a pkg/. $(STAGE)/
	install -D -m 0755 $(BIN) $(STAGE)/usr/bin/gitea-runner
	sed -i -e 's|@VERSION@|$(VERSION)|' -e 's|@REVISION@|$(REVISION)|' \
	       $(STAGE)/DEBIAN/control
	chmod 0755 $(STAGE)/DEBIAN/postinst $(STAGE)/DEBIAN/prerm $(STAGE)/DEBIAN/postrm
	dpkg-deb --root-owner-group --build $(STAGE) $@

clean:
	rm -rf build