#!/usr/bin/make -f
#export DH_VERBOSE = 1

export GOCACHE=$(shell mktemp -d /tmp/gocache-XXXX)

WIN_ARCHS := amd64 arm64
WIN_GOFLAGS := -ldflags=-X=github.com/ubuntu/adsys/internal/consts.Version=$(shell dpkg-parsechangelog -S Version) --mod=vendor
export GOFLAGS := $(WIN_GOFLAGS) -buildmode=pie

# PIE on Windows is only supported for amd64
ifeq ($(shell dpkg --print-architecture),amd64)
	WIN_GOFLAGS += -buildmode=pie
endif

# Only build adwatchd on supported architectures
ifneq ($(filter $(shell dpkg --print-architecture),$(WIN_ARCHS)),)
	WINDOWS_BUILD := 1
endif

# Copy in build directory all content to embed
export DH_GOLANG_INSTALL_ALL := 1

# Skip integration tests when building package: they need docker images
export ADSYS_SKIP_INTEGRATION_TESTS=1

# Skip tests that require sudo: they will run as part of autopkgtests
export ADSYS_SKIP_SUDO_TESTS=1

# Run with Go 1.18
export PATH := /usr/lib/go-1.18/bin/:$(PATH)

%:
	dh $@ --buildsystem=golang --with=golang,apport

override_dh_auto_clean:
	dh_auto_clean
	# Create the vendor directory when building the source package
	[ -d vendor/ ] || go mod vendor

override_dh_auto_build:
	# Build on linux only adsysd itself, and not generator or Windows binaries
	DH_GOLANG_BUILDPKG=github.com/ubuntu/adsys/cmd/adsysd dh_auto_build

# Build the Windows executables for adwatchd where applicable
ifeq ($(WINDOWS_BUILD),1)
	GOFLAGS="$(WIN_GOFLAGS)" GOOS=windows DH_GOLANG_BUILDPKG=github.com/ubuntu/adsys/cmd/adwatchd dh_auto_build
endif

override_dh_auto_install:
	dh_auto_install -- --no-source

	# PAM configuration
	mkdir -p debian/tmp/usr/share/pam
	cp -a pam/pam-configs debian/tmp/usr/share

	# systemd services
	mkdir -p debian/tmp/lib/systemd/system debian/tmp/usr/lib/systemd/user
	cp -a systemd/*.mount debian/tmp/lib/systemd/system/
	cp -a systemd/*.service debian/tmp/lib/systemd/system/
	cp -a systemd/*.socket debian/tmp/lib/systemd/system/
	cp -a systemd/*.timer debian/tmp/lib/systemd/system/
	cp -a systemd/user/*.service debian/tmp/usr/lib/systemd/user/

# Separate windows binaries
ifeq ($(WINDOWS_BUILD),1)
	mkdir -p debian/tmp/usr/share/adsys/windows
	mv debian/tmp/usr/bin/windows_*/* debian/tmp/usr/share/adsys/windows
	rmdir debian/tmp/usr/bin/windows_*

	# Ship admx/adml for ubuntu
	cp -a policies/Ubuntu debian/tmp/usr/share/adsys/windows/policies
endif

	# Install in /sbin
	mv debian/tmp/usr/bin/ debian/tmp/sbin
	# Create adsysctl command
	ln -s adsysd debian/tmp/sbin/adsysctl
	# Run go generate to install assets, but don’t regenerate them
	GENERATE_ONLY_INSTALL_TO_DESTDIR=$(CURDIR)/debian/tmp go generate -x -tags tools $(GOFLAGS) ./...
