#!/usr/bin/make -f
# -*- makefile -*-
#
# These rules should work for any debian-ish distro that is *not*
# systemd based but can use a tweaked, deputy systemd. This includes
# just Ubuntu 14.04 ("trusty"), to our knowledge (let us know if
# you're using this elsewhere!). The more general, systemd-based one
# is the 16.04 rule.
#
# Please keep the diff between that and this relatively small, even if
# it means having suboptimal code; these need to be kept in sync by
# sentient bags of meat.

#export DH_VERBOSE=1
export DH_OPTIONS
export DH_GOPKG := github.com/snapcore/snapd
#export DEB_BUILD_OPTIONS=nocheck
export DH_GOLANG_EXCLUDES=tests
export DH_GOLANG_GO_GENERATE=1

export PATH:=${PATH}:${CURDIR}
# make sure that correct go version is found on trusty
export PATH:=/usr/lib/go-1.18/bin:${PATH}
# GOCACHE is needed by go-1.13+
export GOCACHE:=/tmp/go-build

include /etc/os-release

# On trusty we are relying on a deputy systemd, which does not run as
# PID 1. To solve the problem of services shipping systemd units and
# upstart jobs being started twice, we altered systemd on trusty to
# ignore /lib/systemd/system and instead consider only selected units
# from /lib/systemd/upstart.
SYSTEMD_UNITS_DESTDIR="lib/systemd/upstart/"

# The go tool does not fully support vendoring with gccgo, but we can
# work around that by constructing the appropriate -I flag by hand.
GCCGO := $(shell go tool dist env > /dev/null 2>&1 && echo no || echo yes)

BUILDFLAGS:=-pkgdir=$(CURDIR)/_build/std
# Disable -buildmode=pie mode on all our 32bit platforms
# (i386 and armhf). For i386 because of LP: #1711052 and for
# armhf because of LP: #1822738
ifeq ($(shell dpkg-architecture -qDEB_HOST_ARCH_BITS),64)
 BUILDFLAGS+= -buildmode=pie
endif

GCCGOFLAGS=
ifeq ($(GCCGO),yes)
GOARCH := $(shell go env GOARCH)
GOOS := $(shell go env GOOS)
BUILDFLAGS:=
GCCGOFLAGS=-gccgoflags="-I $(CURDIR)/_build/pkg/gccgo_$(GOOS)_$(GOARCH)/$(DH_GOPKG)/vendor"
export DH_GOLANG_GO_GENERATE=0
endif

# check if we need to include the testkeys in the binary
# TAGS are the go build tags for all binaries, SNAP_TAGS are for snap
# build only.
TAGS=
SNAP_TAGS=
ifneq (,$(filter testkeys,$(DEB_BUILD_OPTIONS)))
	TAGS=-tags withtestkeys
	SNAP_TAGS=-tags "nomanagers withtestkeys"
else
	SNAP_TAGS=-tags nomanagers
endif

BUILT_USING_PACKAGES=
# export DEB_BUILD_MAINT_OPTIONS = hardening=+all
# DPKG_EXPORT_BUILDFLAGS = 1
# include /usr/share/dpkg/buildflags.mk

# Currently, we enable confinement for Ubuntu only, not for derivatives,
# because derivatives may have different kernels that don't support all the
# required confinement features and we don't to mislead anyone about the
# security of the system.  Discuss a proper approach to this for downstreams
# if and when they approach us.
# NOTE this could be simpler for trusty, but this way keeps the diff down.
ifeq ($(shell dpkg-vendor --query Vendor),Ubuntu)
    # On Ubuntu 16.04 we need to produce a build that can be used on wide
    # variety of systems. As such we prefer static linking over dynamic linking
    # for stability, predicability and easy of deployment. We need to link some
    # things dynamically though: udev has no stable IPC protocol between
    # libudev and udevd so we need to link with it dynamically.
    VENDOR_ARGS=--enable-nvidia-multiarch --enable-static-libcap --enable-static-libapparmor --enable-static-libseccomp
    BUILT_USING_PACKAGES=libcap-dev libapparmor-dev libseccomp-dev
else
ifeq ($(shell dpkg-vendor --query Vendor),Debian)
    VENDOR_ARGS=--disable-apparmor --disable-seccomp
    BUILT_USING_PACKAGES=libcap-dev
else
    VENDOR_ARGS=--disable-apparmor
endif
endif
BUILT_USING=$(shell dpkg-query -f '$${source:Package} (= $${source:Version}), ' -W $(BUILT_USING_PACKAGES))

%:
	dh $@ --buildsystem=golang --with=golang --fail-missing --builddirectory=_build

override_dh_fixperms:
	dh_fixperms -Xusr/lib/snapd/snap-confine


# trusty doesn't need the .real workaround
override_dh_installdeb:
	dh_apparmor --profile-name=usr.lib.snapd.snap-confine -psnapd
	dh_installdeb

override_dh_clean:
	dh_clean
	$(MAKE) -C data clean
	# XXX: hacky
	$(MAKE) -C cmd distclean || true
	# Switch back to stock seccomp bindings
	rm -f cmd/snap-seccomp/old_seccomp.go
	sed -i 's|"github.com/mvo5/libseccomp-golang"|"github.com/seccomp/libseccomp-golang"|' cmd/snap-seccomp/*.go

override_dh_auto_build:
	# usually done via `go generate` but that is not supported on powerpc
	./mkversion.sh
	# Switch to mvo5 fork of seccomp bindings that work with old libseccomp
	sed -i 's|"github.com/seccomp/libseccomp-golang"|"github.com/mvo5/libseccomp-golang"|' cmd/snap-seccomp/*.go

	# Build golang bits
	mkdir -p _build/src/$(DH_GOPKG)/cmd/snap/test-data
	cp -a cmd/snap/test-data/*.gpg _build/src/$(DH_GOPKG)/cmd/snap/test-data/
	cp -a bootloader/assets/data _build/src/$(DH_GOPKG)/bootloader/assets
	GOINVOKEFLAGS='-mod=vendor'	GO111MODULE=on \
		dh_auto_build -- -mod=vendor $(BUILDFLAGS) $(TAGS) $(GCCGOFLAGS) $(DH_GOPKG)/cmd/...

	(cd _build/bin && GOPATH=$$(pwd)/.. go build -mod=vendor $(BUILDFLAGS) $(GCCGOFLAGS) $(SNAP_TAGS) $(DH_GOPKG)/cmd/snap)

	# Generate static snap-exec, snapctl and snap-udpate-ns - it somehow includes CGO so we must
	# force a static build here. We need a static snap-{exec,update-ns}/snapctl inside
	# the core snap because not all bases will have a libc
	(cd _build/bin && GOPATH=$$(pwd)/.. CGO_ENABLED=0 go build -mod=vendor $(GCCGOFLAGS) $(DH_GOPKG)/cmd/snap-exec)
	(cd _build/bin && GOPATH=$$(pwd)/.. CGO_ENABLED=0 go build -mod=vendor $(GCCGOFLAGS) $(DH_GOPKG)/cmd/snapctl)
	(cd _build/bin && GOPATH=$$(pwd)/.. go build -mod=vendor --ldflags '-extldflags "-static"' $(GCCGOFLAGS) $(DH_GOPKG)/cmd/snap-update-ns)
	# ensure we generated a static build
	$(shell	if ldd _build/bin/snap-exec; then false "need static build"; fi)
	$(shell	if ldd _build/bin/snap-update-ns; then false "need static build"; fi)
	$(shell	if ldd _build/bin/snapctl; then false "need static build"; fi)

	# Build C bits, sadly manually
	cd cmd && ( autoreconf -i -f )
	cd cmd && ( ./configure --prefix=/usr --libexecdir=/usr/lib/snapd $(VENDOR_ARGS))
	$(MAKE) -C cmd all

	# Generate the real systemd/dbus/env config files
	$(MAKE) -C data all

override_dh_auto_test:
	GO111MODULE=on \
		dh_auto_test -- -mod=vendor $(BUILDFLAGS) $(TAGS) $(GCCGOFLAGS) $(DH_GOPKG)/...
# a tested default (production) build should have no test keys
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	# check that only the main trusted account-keys are included
	[ $$(strings _build/bin/snapd|grep -c -E "public-key-sha3-384: [a-zA-Z0-9_-]{64}") -eq 2 ]
	strings _build/bin/snapd|grep -c "^public-key-sha3-384: -CvQKAwRQ5h3Ffn10FILJoEZUXOv6km9FwA80-Rcj-f-6jadQ89VRswHNiEB9Lxk$$"
	strings _build/bin/snapd|grep -c "^public-key-sha3-384: d-JcZF9nD9eBw7bwMnH61x-bklnQOhQud1Is6o_cn2wTj8EYDi9musrIT9z2MdAa$$"
	# same for snap-repair
	[ $$(strings _build/bin/snap-repair|grep -c -E "public-key-sha3-384: [a-zA-Z0-9_-]{64}") -eq 3 ]
	# common with snapd
	strings _build/bin/snap-repair|grep -c "^public-key-sha3-384: -CvQKAwRQ5h3Ffn10FILJoEZUXOv6km9FwA80-Rcj-f-6jadQ89VRswHNiEB9Lxk$$"
	strings _build/bin/snap-repair|grep -c "^public-key-sha3-384: d-JcZF9nD9eBw7bwMnH61x-bklnQOhQud1Is6o_cn2wTj8EYDi9musrIT9z2MdAa$$"
	# repair-root
	strings _build/bin/snap-repair|grep -c "^public-key-sha3-384: nttW6NfBXI_E-00u38W-KH6eiksfQNXuI7IiumoV49_zkbhM0sYTzSnFlwZC-W4t$$"
endif
ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
	# run the snap-confine tests
	$(MAKE) -C cmd check
endif

override_dh_install:
	# we do not need this in the package, its just needed during build
	rm -rf ${CURDIR}/debian/tmp/usr/bin/xgettext-go
	# toolbelt is not shippable
	rm -f ${CURDIR}/debian/tmp/usr/bin/toolbelt
	# we do not like /usr/bin/snappy anymore
	rm -f ${CURDIR}/debian/tmp/usr/bin/snappy
	# snap-bootstrap is only useful on core (and we don't have a 14.04 core)
	rm -f ${CURDIR}/debian/tmp/usr/bin/snap-bootstrap
	# snap-keymgr is not useful either
	rm -f ${CURDIR}/debian/tmp/usr/bin/snap-fde-keymgr
	# same goes for snap-recovery-chooser
	rm -f ${CURDIR}/debian/tmp/usr/bin/snap-recovery-chooser
	# i18n stuff
	mkdir -p debian/snapd/usr/share
	if [ -d share/locale ]; then \
		cp -R share/locale debian/snapd/usr/share; \
	fi
	# chrorder generator
	rm -f ${CURDIR}/debian/tmp/usr/bin/chrorder
	# bootloader assets generator
	rm -f ${CURDIR}/debian/tmp/usr/bin/genasset
	# asserts/info
	rm -f ${CURDIR}/debian/tmp/usr/bin/info
	# docs generator
	rm -f ${CURDIR}/debian/tmp/usr/bin/docs

	# Install snapd's systemd units / upstart jobs, done
	# here instead of debian/snapd.install because the
	# ubuntu/14.04 release branch adds/changes bits here
	$(MAKE) -C data install DESTDIR=$(CURDIR)/debian/snapd/ \
		SYSTEMDSYSTEMUNITDIR=$(SYSTEMD_UNITS_DESTDIR)
	# We called this apps-bin-path.sh instead of snapd.sh, and
	# it's a conf file so we're stuck with it
	mv debian/snapd/etc/profile.d/snapd.sh debian/snapd/etc/profile.d/apps-bin-path.sh

	# trusty needs this to make /snap rshared
	install --mode=0644 debian/snap.mount.service debian/snapd/$(SYSTEMD_UNITS_DESTDIR)

	$(MAKE) -C cmd install DESTDIR=$(CURDIR)/debian/tmp

	# trusty doesn't need the .real workaround

	# On Ubuntu and Debian we don't need to install the apparmor helper service.
	rm $(CURDIR)/debian/snapd/$(SYSTEMD_UNITS_DESTDIR)/snapd.apparmor.service
	rm $(CURDIR)/debian/tmp/usr/bin/snapd-apparmor

	# Remove prompt services, not used on 14.04
	rm $(CURDIR)/debian/snapd/$(SYSTEMD_UNITS_DESTDIR)/snapd.aa-prompt-listener.service
	rm $(CURDIR)/debian/snapd/usr/lib/systemd/user/snapd.aa-prompt-ui.service
	rm $(CURDIR)/debian/snapd/usr/share/dbus-1/services/io.snapcraft.Prompt.service
	rm $(CURDIR)/debian/tmp/usr/bin/snapd-aa-prompt-listener
	rm $(CURDIR)/debian/tmp/usr/bin/snapd-aa-prompt-ui

	dh_install

override_dh_auto_install: snap.8
	dh_auto_install -O--buildsystem=golang

override_dh_golang:
	# XXX: dh_golang on older versions of ubuntu is not capable to
	# deal with newer go and go.mod. So just make this a no-op or
	# things will fail on e.g. 18.04. dh_golang will only add
	# "misc:Built-Using" information.
	true

snap.8:
	$(CURDIR)/_build/bin/snap help --man > $@

override_dh_auto_clean:
	# XXX: workaround old dh-golang inability to remove _build/
	if [ -d _build ]; then cd _build && GOPATH=$$(pwd) go clean -modcache; fi
	dh_auto_clean -O--buildsystem=golang
	rm -vf snap.8

override_dh_gencontrol:
	dh_gencontrol -- -VBuilt-Using="$(BUILT_USING)"
