#!/bin/sh

set -e

if [ "$1" = "configure" ]; then
	# docker.socket activates the default docker instance running
	# outside a vrf. In order to have docker running inside the
	# mgmt vrf via systemd-vrf-generator, rely on normal service
	# activation (`systemctl start docker@mgmt.service`).
	deb-systemd-helper disable docker.socket
	# Use systemctl directly to avoid interference from
	# /etc/apt/apt.conf.d/25policy-no-stop-start
	if systemctl is-active --quiet docker.socket; then
		systemctl stop docker.socket
	fi
	# Disable docker by default. docker@mgmt.service should be
	# enabled by the administrator if desired.
	deb-systemd-helper disable docker.service
	if systemctl is-active --quiet docker.service; then
		systemctl stop docker.service
	fi
	deb-systemd-helper disable containerd.service
	if systemctl is-active --quiet containerd.service; then
		systemctl stop containerd.service
	fi
fi

if [ "$1" = "configure" -o "$1" = "abort-remove" ]; then
	# adapted from /usr/share/debhelper/autoscripts/displace.sh.in
	# We cannot use the "displace" operation directly because having a
	# service file be a symlink does not work well with systemd (at least
	# the version in Buster).
	package=cumulus-docker-setup
	file=/lib/systemd/system/docker.service
	theirfile=/usr/lib/cumulus/docker.service.dist
	ourfile=/usr/lib/cumulus/docker.service

	if ! LC_ALL=C dpkg-divert --list "$package" | \
		grep -xFq "diversion of $file to $theirfile by $package"; then
			dpkg-divert --divert "$theirfile" --rename \
				--package "$package" --add "$file"
	fi
	cp -a "$ourfile" "$file"
	# This leads systemd-vrf-generator to regenerate
	# /etc/systemd/system/docker@.service based on the newly installed
	# docker.service.
	systemctl daemon-reload
fi

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
