# pacman install script of plinius-dnsfilter: /etc/resolv.conf becomes a link to
# /run/plinius-dns/resolv.conf, which leads to NetworkManager's file while the filter is off.
# NetworkManager (rc-manager=symlink) leaves a link it did not make alone. On removal the
# phone gets NetworkManager's own link back.
#
# The filter is on from the start: a fresh install (also every new image) writes settings with
# the filter on, unless there are some already. An update never switches it, so a phone where it
# was switched off keeps it off. The service reads them at its next start.

_settings=/var/lib/plinius-dnsfilter/settings

_switch_on() {
	[[ -e $_settings ]] && return 0
	mkdir -p "${_settings%/*}"
	chmod 700 "${_settings%/*}"
	(umask 077 && printf '%s\n' '# plinius-dnsfilter: on from the start (plinius-dnsfilter.install)' \
		'[filter]' 'enabled=true' >"$_settings")
}

_link() {
	systemd-tmpfiles --create plinius-dnsfilter.conf 2>/dev/null || true
	if [ "$(readlink /etc/resolv.conf)" != /run/plinius-dns/resolv.conf ]; then
		ln -sfn /run/plinius-dns/resolv.conf /etc/resolv.conf
	fi
}

post_install() {
	_link
	_switch_on
}

post_upgrade() {
	_link
	# Before 0.1-4 the query log and statistics were world-readable
	chmod -R go-rwx /var/lib/plinius-dnsfilter 2>/dev/null || true
	# A running filter gets the new version; one that is off is started on demand anyway
	if systemctl -q is-active plinius-dnsfilter.service 2>/dev/null; then
		# pacman's own daemon-reload hook only runs after this script
		systemctl daemon-reload || true
		systemctl try-restart plinius-dnsfilter.service || true
	fi
}

pre_remove() {
	systemctl stop plinius-dnsfilter.service 2>/dev/null || true
	/usr/bin/plinius-dnsfilter --cleanup 2>/dev/null || true
	ln -sfn /run/NetworkManager/resolv.conf /etc/resolv.conf
	return 0
}
