#!/usr/bin/make -f

export GOCACHE = $(CURDIR)/.cache/go-build
export GOPATH = $(CURDIR)/.go
export HOME = $(CURDIR)

DEB_VERSION := $(shell dpkg-parsechangelog -S Version)
UPSTREAM_VERSION := $(shell echo $(DEB_VERSION) | sed -E 's/\+[0-9.]+$$//; s/\.db[0-9]*$$//' | sed 's/ppa[0-9]*$$//')
COMMIT_HASH := $(shell echo $(UPSTREAM_VERSION) | sed -n 's/.*\.\([a-f0-9]\{8\}\)$$/\1/p')
BUILD_TIME := $(shell date -u '+%Y-%m-%d_%H:%M:%S')

DEB_HOST_ARCH := $(shell dpkg-architecture -qDEB_HOST_ARCH)
GO_HOST_ARCH := $(if $(filter arm64,$(DEB_HOST_ARCH)),arm64,amd64)
export PATH := $(CURDIR)/.go-toolchain/$(GO_HOST_ARCH)/go/bin:$(PATH)

%:
	dh $@

override_dh_auto_build:
	# Embed the quickshell UI and build it into the binary.
	$(MAKE) -C core sync-shell
	cd core && \
		GOTOOLCHAIN=local CGO_ENABLED=0 go build -mod=vendor \
		-tags withshell \
		-ldflags="-s -w -X main.Version=$(UPSTREAM_VERSION) -X main.BuildTime=$(BUILD_TIME) -X main.Commit=$(COMMIT_HASH)" \
		-o ../dfiles ./cmd/dfiles
	mkdir -p completions
	./dfiles completion bash > completions/dfiles
	./dfiles completion zsh > completions/_dfiles
	./dfiles completion fish > completions/dfiles.fish

override_dh_auto_install:
	install -Dm755 dfiles debian/dux-files-git/usr/bin/dfiles
	install -Dm644 assets/systemd/dfiles.service debian/dux-files-git/usr/lib/systemd/user/dfiles.service
	install -Dm644 assets/dev.duxlabs.files.desktop \
		debian/dux-files-git/usr/share/applications/dev.duxlabs.files.desktop
	install -Dm644 assets/dev.duxlabs.files.svg \
		debian/dux-files-git/usr/share/icons/hicolor/scalable/apps/dev.duxlabs.files.svg
	install -Dm644 assets/dev.duxlabs.files.metainfo.xml \
		debian/dux-files-git/usr/share/metainfo/dev.duxlabs.files.metainfo.xml
	install -Dm644 assets/dev.duxlabs.files.policy \
		debian/dux-files-git/usr/share/polkit-1/actions/dev.duxlabs.files.policy
	install -Dm644 assets/dbus/dev.duxlabs.files.FileManager1.service \
		debian/dux-files-git/usr/share/dbus-1/services/dev.duxlabs.files.FileManager1.service
	install -Dm644 assets/dbus/org.freedesktop.impl.portal.desktop.dfiles.service \
		debian/dux-files-git/usr/share/dbus-1/services/org.freedesktop.impl.portal.desktop.dfiles.service
	install -Dm644 assets/portal/dfiles.portal \
		debian/dux-files-git/usr/share/xdg-desktop-portal/portals/dfiles.portal
	install -Dm644 completions/dfiles \
		debian/dux-files-git/usr/share/bash-completion/completions/dfiles
	install -Dm644 completions/_dfiles \
		debian/dux-files-git/usr/share/zsh/site-functions/_dfiles
	install -Dm644 completions/dfiles.fish \
		debian/dux-files-git/usr/share/fish/vendor_completions.d/dfiles.fish

# D-Bus activation starts dfiles on demand; the session unit is opt-in.
override_dh_installsystemduser:
	dh_installsystemduser --no-enable

override_dh_auto_test:
	# Skip tests for git snapshot packaging

override_dh_auto_clean:
	rm -rf dfiles completions .cache .go core/internal/shellembed/dist
	dh_auto_clean
