#!/usr/bin/make -f

# internal/buildcheck is a no-op program that only exists for upstream CI.
export DH_GOLANG_EXCLUDES := internal/buildcheck

%:
	dh $@ --builddirectory=debian/_build --buildsystem=golang --with=golang

# dh-go 1.69 go.work defects (see trivy-kubernetes): replaced directories
# without go.mod (https://bugs.debian.org/1149023), json-patch/v5 not mapped,
# diskv v3 installed at the v2 path; Debian's k8s also imports json-patch/v5
# and cel.dev/cel-go without requiring them in go.mod.
execute_after_dh_auto_configure:
	[ ! -e debian/_build/go.work ] || $(MAKE) -f debian/rules fix-go-work

# autopkgtest overrides dh_auto_configure, so dh-go would only write go.work
# inside dh_auto_build; write it with dh-go's own code first and fix it.
execute_before_dh_auto_build:
	[ -e debian/_build/go.work ] || { $(MAKE) -f debian/rules write-go-work && \
	  $(MAKE) -f debian/rules fix-go-work; }

WRITE_GO_WORK := buildsystems_init(); my $$b = load_buildsystem("golang"); \
	$$b->pre_building_step("build"); $$b->_setup_module_mappings(); \
	$$b->_construct_modules("/usr/share/gocode/src", $$b->get_buildpath("src"), 0); \
	$$b->_create_go_work_file();
write-go-work:
	perl -MDebian::Debhelper::Dh_Buildsystems -e '$(WRITE_GO_WORK)' \
	  -- --builddirectory=debian/_build

fix-go-work:
	cd debian/_build && sed -n 's|^replace \(\S*\) => \./src/\(\S*\)$$|\1 \2|p' go.work | \
	while read m d; do \
		[ ! -e src/$$d/go.mod ] || continue; \
		v=$$(go env GOVERSION | sed -E 's/^go([0-9]+\.[0-9]+).*/\1/'); \
		r=$$(realpath src/$$d); \
		case $$r in \
		$$(realpath .)/*) printf 'module %s\n\ngo %s\n' $$m $$v > src/$$d/go.mod ;; \
		*) mkdir -p src/COMPAT/$$m && ln -s $$r/* src/COMPAT/$$m/ && \
		   printf 'module %s\n\ngo %s\n' $$m $$v > src/COMPAT/$$m/go.mod && \
		   sed -i "s|^replace $$m => .*|replace $$m => ./src/COMPAT/$$m|" go.work ;; \
		esac; \
	done
	cd debian/_build && \
	  go mod edit -require=github.com/evanphx/json-patch/v5@v5.7.0 -require=cel.dev/cel-go@v0.32.0 src/github.com/fluxcd/cli-utils/go.mod && \
	  echo 'replace github.com/evanphx/json-patch/v5 => ./src/github.com/evanphx/json-patch/v5' >> go.work
	mkdir -p debian/_build/src/COMPAT/github.com/peterbourgon/diskv
	cd debian/_build/src/COMPAT/github.com/peterbourgon/diskv && \
	  ln -s /usr/share/gocode/src/github.com/peterbourgon/diskv/*.go . && \
	  sed 's|^module .*|module github.com/peterbourgon/diskv|' \
	    /usr/share/gocode/src/github.com/peterbourgon/diskv/go.mod > go.mod
	sed -i 's|^replace github.com/peterbourgon/diskv => .*|replace github.com/peterbourgon/diskv => ./src/COMPAT/github.com/peterbourgon/diskv|' \
	  debian/_build/go.work
