#!/bin/bash

INITSYS=`readlink -f /proc/1/exe`
if [ "$INITSYS" != "/lib/systemd/systemd" -a "$INITSYS" != "/usr/lib/systemd/systemd" ]; then
	echo "ERROR: This chr package supports only systemd."
	exit 0
fi

# create bind user
getent group bind >/dev/null 2>&1 ||
	addgroup --system bind
getent passwd bind >/dev/null 2>&1 ||
	adduser --system --home /var/cache/bind --no-create-home --disabled-password --shell /bin/false --ingroup bind bind


echo "Checking systemd notify,log socket placeholders"
/usr/lib/3gsystools/chr_placeholder_check /chroot/named/run /systemd/notify file
/usr/lib/3gsystools/chr_placeholder_check /chroot/named/run /systemd/journal/dev-log file

# restarting syslog
systemctl restart rsyslog

# creating link from /dev/log to systemd log socket
if ! [ -e /chroot/named/dev/log ]; then
	ln -s ../run/systemd/journal/dev-log /chroot/named/dev/log
fi

echo "Updating fstab"
/usr/local/sbin/fstab-chr

# delete deprecated units
[ -h /etc/systemd/system/multi-user.target.wants/bind9-chroot.service ] && rm /etc/systemd/system/multi-user.target.wants/bind9-chroot.service

# activating systemd units
systemctl daemon-reload


# Enabling systemd units

SYSTEMD_UNITS="
	chr-named.target
	chroot-named-run-systemd-notify.mount
	chroot-named-tmp.mount
	chroot-named-run-systemd-journal-dev\\x2dlog.mount
	bind9-chroot.service
"

for systemd_unit in $SYSTEMD_UNITS; do

	systemctl enable "${systemd_unit}"
	if deb-systemd-helper --quiet was-enabled "${systemd_unit}"; then
		deb-systemd-helper enable "${systemd_unit}" >/dev/null || true
	else
		deb-systemd-helper update-state "${systemd_unit}" >/dev/null || true
	fi

done

exit 0
