PREFIX    ?= /usr
DESTDIR   ?=

# Daemon goes under libexec — not on $PATH; D-Bus / systemd activation
# is how the rest of the session reaches it. Matches the convention the
# other Liberux daemons follow.
LIBEXECDIR = $(DESTDIR)$(PREFIX)/libexec
DATADIR    = $(DESTDIR)$(PREFIX)/share
SYSTEMDDIR = $(DESTDIR)$(PREFIX)/lib/systemd/user

DBUS_DIR   = $(DATADIR)/dbus-1/services

# RUST_TARGET selects the cargo target triple. Empty = native build.
# When set (e.g. aarch64-unknown-linux-gnu) both the build and the
# install pick up the per-target output directory, so a cross-compiled
# binary is what gets staged into the package.
RUST_TARGET ?=
CARGO_TARGET_FLAG = $(if $(RUST_TARGET),--target $(RUST_TARGET),)
TARGET_DIR        = target/$(if $(RUST_TARGET),$(RUST_TARGET)/,)release
BIN               = $(TARGET_DIR)/contacts-server

.PHONY: all start install uninstall clean distclean arm64 arm64-deps deb deb-arm64

all:
	cargo build --release $(CARGO_TARGET_FLAG)

start: all
	./$(BIN)

# One-off host packages needed to cross-compile and link for arm64 from
# an amd64 host: the cross gcc (pulls the arm64 sysroot libc headers the
# bundled SQLite cc build needs) and the arm64 Rust standard library.
arm64-deps:
	sudo dpkg --add-architecture arm64
	sudo apt-get update
	sudo apt-get install gcc-aarch64-linux-gnu libstd-rust-dev:arm64 libstd-rust-1.85:arm64

arm64:
	$(MAKE) all RUST_TARGET=aarch64-unknown-linux-gnu

# Build the native .deb.
deb:
	dpkg-buildpackage -us -uc -b

# Cross-build the arm64 .deb from an amd64 host. Run `make arm64-deps` once
# beforehand. The build-arch tools (cargo, rustc) stay native; the host-arch
# build deps and the resulting binary are arm64.
deb-arm64:
	dpkg-buildpackage -us -uc -b --host-arch arm64

install:
	install -Dm755 $(BIN)                                    $(LIBEXECDIR)/contacts-server
	install -Dm644 data/org.liberux.Contacts1.service       $(DBUS_DIR)/org.liberux.Contacts1.service
	install -Dm644 data/contacts-server.service             $(SYSTEMDDIR)/contacts-server.service

uninstall:
	rm -f $(LIBEXECDIR)/contacts-server
	rm -f $(DBUS_DIR)/org.liberux.Contacts1.service
	rm -f $(SYSTEMDDIR)/contacts-server.service

clean:
	cargo clean

distclean: clean
	dh_clean
	rm -f Cargo.lock
