#!/bin/sh
# Jarl: runs after the package's files are in place.
set -e

if [ "$1" = configure ]; then
	# The jarl system user (a member of group bind) and Jarl's directories:
	# /etc/jarl, /var/lib/jarl, /etc/bind/jarl, /var/lib/bind/jarl,
	# /var/cache/bind/jarl and /var/log/named.
	systemd-sysusers jarl.conf
	systemd-tmpfiles --create jarl.conf || true

	# An example configuration on the first install; an existing one is
	# never touched.
	if [ ! -e /etc/jarl/jarl.yaml ]; then
		/usr/bin/jarld config --example > /etc/jarl/jarl.yaml.dpkg-new
		chown root:jarl /etc/jarl/jarl.yaml.dpkg-new
		chmod 0640 /etc/jarl/jarl.yaml.dpkg-new
		mv /etc/jarl/jarl.yaml.dpkg-new /etc/jarl/jarl.yaml
	fi

	# The daily database backup (jarl-backup.timer) is on by default. An
	# administrator's 'systemctl disable jarl-backup.timer' is remembered
	# by deb-systemd-helper and kept across upgrades. Before 'jarld init'
	# the backup skips itself (there is no database yet).
	if command -v deb-systemd-helper >/dev/null 2>&1; then
		deb-systemd-helper unmask jarl-backup.timer >/dev/null || true
		if deb-systemd-helper --quiet was-enabled jarl-backup.timer; then
			deb-systemd-helper enable jarl-backup.timer >/dev/null || true
		else
			deb-systemd-helper update-state jarl-backup.timer >/dev/null || true
		fi
	elif [ -z "$2" ] && [ -d /run/systemd/system ]; then
		systemctl enable jarl-backup.timer >/dev/null 2>&1 || true
	fi

	if [ -d /run/systemd/system ]; then
		systemctl daemon-reload || true
		if systemctl is-enabled --quiet jarl-backup.timer 2>/dev/null; then
			systemctl start jarl-backup.timer || true
		fi
		# The jarld.service alias is linked when jarl.service is enabled;
		# relink a unit enabled before the alias existed (this neither
		# starts nor stops jarld).
		if [ -n "$2" ] && systemctl is-enabled --quiet jarl.service 2>/dev/null \
			&& [ ! -e /etc/systemd/system/jarld.service ]; then
			systemctl reenable jarl.service >/dev/null 2>&1 || true
		fi
		# An upgrade restarts a running jarld (its database is upgraded
		# when it starts). A first install starts nothing: Jarl needs
		# 'jarld init' and 'jarld adopt' first.
		if [ -n "$2" ] && systemctl is-active --quiet jarl.service; then
			systemctl restart jarl.service || echo "jarl: restarting jarld failed; see 'journalctl -u jarl'" >&2
		fi
	fi

	if [ -z "$2" ]; then
		echo "Jarl is installed. Next: create the database and adopt your BIND"
		echo "configuration, as described in /usr/share/doc/jarl/docs/install.md"
		echo "(from step 3), then: systemctl enable --now jarl"
	fi
fi

exit 0
