#!/usr/bin/make -f

export DH_VERBOSE=1

DEB_HOST_ARCH ?= $(shell dpkg-architecture -qDEB_HOST_ARCH)

DEB_VERSION := $(shell dpkg-parsechangelog -SVersion | sed 's/-[0-9]*$$//')
UPSTREAM_VERSION := $(DEB_VERSION)
SOFTWARE_NAME := gitea-runner

export GOTOOLCHAIN=local
export GOPROXY=off
export GOSUMDB=off
export GOMODCACHE=$(CURDIR)/.gomodcache
export CGO_ENABLED=0

%:
	dh $@

override_dh_auto_build:
	@if [ ! -d vendor ]; then \
		echo "vendor/ not found, attempting to extract from SOURCES..."; \
		if [ -f /usr/src/packages/SOURCES/$(SOFTWARE_NAME)-$(UPSTREAM_VERSION)-vendor.tar.gz ]; then \
			tar -xzf /usr/src/packages/SOURCES/$(SOFTWARE_NAME)-$(UPSTREAM_VERSION)-vendor.tar.gz; \
			echo "vendor/ extracted successfully"; \
		else \
			echo "ERROR: vendor tarball not found in /usr/src/packages/SOURCES/"; \
			exit 1; \
		fi; \
	fi

	@test -d vendor || (echo "ERROR: vendor/ directory still not found" && exit 1)

	# `go build` would emit "runner" (module last element); force "gitea-runner".
	go build \
		-v -trimpath \
		-mod=vendor -modcacherw -buildvcs=false \
		-ldflags "-X 'gitea.com/gitea/runner/internal/pkg/ver.version=v$(UPSTREAM_VERSION)' \
		         -s -w -buildid=" \
		-o $(SOFTWARE_NAME) .

	@test -f $(SOFTWARE_NAME) || (echo "ERROR: binary not built" && exit 1)
	@echo "==> Binary built successfully: $(SOFTWARE_NAME)"

	# Chicken-and-egg: the sample config comes from the program itself
	# (`gitea-runner generate-config`). Generate it from the just-built binary.
	./$(SOFTWARE_NAME) generate-config > config.yaml.generated

override_dh_auto_install:
	install -Dm755 $(SOFTWARE_NAME) $(CURDIR)/debian/$(SOFTWARE_NAME)/usr/bin/$(SOFTWARE_NAME)
	install -Dm644 LICENSE $(CURDIR)/debian/$(SOFTWARE_NAME)/usr/share/doc/$(SOFTWARE_NAME)/copyright

	# Systemd service file
	install -Dm644 /usr/src/packages/SOURCES/$(SOFTWARE_NAME).service \
		$(CURDIR)/debian/$(SOFTWARE_NAME)/lib/systemd/system/$(SOFTWARE_NAME).service

	# Sysusers configuration
	install -Dm644 /usr/src/packages/SOURCES/$(SOFTWARE_NAME).sysusers \
		$(CURDIR)/debian/$(SOFTWARE_NAME)/usr/lib/sysusers.d/$(SOFTWARE_NAME).conf

	# Active config under /etc is registered as a dpkg conffile automatically,
	# so user edits survive upgrades. No separate .example is shipped: the binary
	# embeds the sample (`gitea-runner generate-config`).
	install -Dm640 config.yaml.generated \
		$(CURDIR)/debian/$(SOFTWARE_NAME)/etc/$(SOFTWARE_NAME)/config.yaml

	# State directory for the .runner registration file.
	install -d -m750 $(CURDIR)/debian/$(SOFTWARE_NAME)/var/lib/$(SOFTWARE_NAME)

override_dh_auto_test:

override_dh_strip:
