#!/bin/sh
# SPDX-FileCopyrightText: 2022-2025 Helmut Grohne <helmut@subdivi.de>
# SPDX-License-Identifier: MIT
#
# This is a mmdebstrap customize hook that enables systemd-resolved on various
# Debian releases.

set -eu

TARGET=$1

LIBNSS_RESOLVE_VERSION=$(dpkg-query --root "$TARGET" -f '${Version}' -W libnss-resolve 2>/dev/null) || :

if test "${MMDEBSTRAP_MODE:-}" = chrootless; then
	target_apt_get() {
		APT_CONFIG="$MMDEBSTRAP_APT_CONFIG" \
			apt-get \
			-oDPkg::Options::=--force-not-root \
			-oDPkg::Options::=--force-script-chrootless \
			-oDPkg::Options::=--root="$TARGET" \
			-oDPkg::Options::=--log="$TARGET/var/log/dpkg.log"
			"$@"
	}
else
	target_apt_get() {
		APT_CONFIG="$MMDEBSTRAP_APT_CONFIG" \
			apt-get \
			-oDPkg::Chroot-Directory="$TARGET" \
			"$@"
	}
fi

link_resolv_conf() {
	if ! test -e "$TARGET$1" -o -h "$TARGET/etc/resolv.conf"; then
		# To avoid breaking network during mmdebstrap via a dead link, take a copy.
		install -D "$TARGET/etc/resolv.conf" "$TARGET$1"
	fi
	ln -fs "..$1" "$TARGET/etc/resolv.conf"
}

if dpkg --compare-versions "$LIBNSS_RESOLVE_VERSION" lt 251.3-2~exp1; then
	if test "${MMDEBSTRAP_MODE:-}" = chrootless; then
		systemctl --root "$TARGET" enable systemd-resolved.service
	else
		chroot "$TARGET" systemctl enable systemd-resolved.service
	fi

	if test -z "$LIBNSS_RESOLVE_VERSION" || dpkg --compare-versions "$LIBNSS_RESOLVE_VERSION" lt 236; then
		link_resolv_conf /run/systemd/resolve/resolv.conf
	else
		link_resolv_conf /run/systemd/resolve/stub-resolv.conf
	fi
else
	target_apt_get --yes install systemd-resolved
	if test -h "$TARGET/etc/resolv.conf" && ! test -e "$TARGET/etc/resolv.conf"; then
		resolvconftarget=$(readlink "$TARGET/etc/resolv.conf")
		if test "${resolvconftarget#../run/}" != "$resolvconftarget"; then
			# /etc/resolv.conf is a dead link pointing to ../run/*
			# mmdebstrap originally copied /etc/resolv.conf
			# This situation arises when installing systemd-resolved in bookworm
			# Fix network during mmdebstrap.
			install -D /etc/resolv.conf "$TARGET${resolvconftarget#..}"
		fi
	fi
fi
