#!/usr/bin/env bash
### Point the system resolver at the local dnscrypt-proxy (127.0.2.1).
### Prefer the resolvconf method, which works with openresolv (20.04/22.04) and
### keeps the stock behaviour. On systemd-resolved (24.04) `resolvconf -a lo` is a
### resolvectl wrapper that refuses the loopback link ("Link lo is loopback
### device") and returns non-zero, which killed dnscrypt-proxy's ExecStartPost;
### there we fall back to a static /etc/resolv.conf symlink. Called from the
### dnscrypt-proxy service drop-in.

DC_IP=127.0.2.1
RUN_RESOLV=/run/hive-dnscrypt-resolv.conf
# relative target, matching how systemd-resolved ships /etc/resolv.conf
STUB=../run/systemd/resolve/stub-resolv.conf

case "$1" in
	up)
		# openresolv path: registers 127.0.2.1 and updates /etc/resolv.conf itself
		printf 'nameserver %s\n' "$DC_IP" | /sbin/resolvconf -a lo 2>/dev/null && exit 0
		# systemd-resolved path: bypass the failing shim with a static resolver file
		printf 'nameserver %s\noptions edns0\n' "$DC_IP" > "$RUN_RESOLV"
		ln -sf "$RUN_RESOLV" /etc/resolv.conf
		;;
	down)
		/sbin/resolvconf -d lo 2>/dev/null
		# undo the static symlink only if we set it (never clobber openresolv)
		[[ "$(readlink /etc/resolv.conf 2>/dev/null)" == "$RUN_RESOLV" ]] &&
			ln -sf "$STUB" /etc/resolv.conf
		rm -f "$RUN_RESOLV"
		;;
	*)
		echo "Usage: $0 up|down" >&2
		exit 1
		;;
esac
exit 0
