set -e

systemctl_stop() {
	unit="$1"

	echo "Stopping unit $unit"
	systemctl stop -q "$unit" || true

	for i in $(seq 20); do
		echo "Waiting until unit $unit is stopped [attempt $i]"
		if ! systemctl is-active -q "$unit"; then
			echo "$unit is stopped."
			return
		fi
		sleep .1
	done
}

units=$(systemctl list-unit-files --full | grep '^snap\.' | cut -f1 -d ' ' | grep -vF snap.mount.service || true)
tostop=$(echo "$units" | grep -E '^snap\..*\.(service|timer|socket)$' || true)

for unit in $tostop; do
	# ensure it's really a snap mount unit or systemd unit
	if  ! grep -q 'X-Snappy=yes' "/etc/systemd/system/$unit"; then
		echo "Skipping non-snapd systemd unit $unit"
		continue
	fi

	echo "Stopping $unit"
	systemctl stop "$unit"
done
