#!/usr/bin/make -f
include /usr/share/dpkg/pkg-info.mk
export DH_VERBOSE = 1
export DEB_BUILD_MAINT_OPTIONS = optimize=-lto
export GOTOOLCHAIN := local
export INSIGHTS_GO_PACKAGE := $(shell grep-dctrl -s XS-Go-Import-Path -n - ./debian/control)
export GOFLAGS := -ldflags=-X=$(INSIGHTS_GO_PACKAGE)/internal/constants.Version=$(DEB_VERSION_UPSTREAM) --mod=vendor -buildmode=pie
export DH_GOLANG_GO_GENERATE := 1

BUILDDIR := _build
DESTDIR := $(CURDIR)/debian/tmp
DEB_VERSION_MAJOR := $(shell echo $(DEB_VERSION_UPSTREAM) | cut -d. -f1)
GENERATED_DIR := $(BUILDDIR)/src/$(INSIGHTS_GO_PACKAGE)/generated

%:
ifeq ($(strip $(shell ./debian/prepare-source.sh)),)
	@echo "Vendoring probably failed"
	exit 1
endif
	dh $@ --builddirectory=$(BUILDDIR) --buildsystem=golang --with=golang

override_dh_auto_install:
	# Do not ship the library resulting binary cmdline, but we still want it in the package list to run the tests.
	rm $(BUILDDIR)/bin/C
	
	install -d $(DESTDIR)/usr
	mv $(BUILDDIR)/bin/insights $(BUILDDIR)/bin/ubuntu-insights
	cp -a $(GENERATED_DIR)/usr/. $(DESTDIR)/usr/

	# libinsights
	install -Dm755 $(GENERATED_DIR)/libinsights.so.$(DEB_VERSION_MAJOR) $(DESTDIR)/usr/lib/$(DEB_HOST_MULTIARCH)/libinsights.so.$(DEB_VERSION_MAJOR)
	ln -s libinsights.so.$(DEB_VERSION_MAJOR) $(DESTDIR)/usr/lib/$(DEB_HOST_MULTIARCH)/libinsights.so

	install -Dm644 $(GENERATED_DIR)/types.h $(DESTDIR)/usr/include/insights/types.h
	install -Dm644 $(GENERATED_DIR)/insights.h $(DESTDIR)/usr/include/insights/insights.h
	install -d $(DESTDIR)/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig
	sed -e s/@DEB_HOST_MULTIARCH@/$(DEB_HOST_MULTIARCH)/ -e s/@VERSION@/$(DEB_VERSION_UPSTREAM)/ debian/insights.pc.in > $(DESTDIR)/usr/lib/$(DEB_HOST_MULTIARCH)/pkgconfig/insights.pc

	dh_auto_install -- --no-source
