# The container service runs from boot on, so that an Android app starts from the app grid like
# any other (it starts Android only with the first app; until Waydroid is initialised, its
# condition keeps it from starting at all). Enabled once: on installing, or on the update that
# brought this; a choice made since stays.
#
# The AppArmor profile that keeps Android's root inside the container (plinius.waydroid) is
# loaded at once, so that the next start of the container has it (at boot plinius-apparmor loads
# it anyway; in the image build there is no systemd, which changes nothing).
load_profile() {
	systemctl reload plinius-apparmor.service 2>/dev/null || true
}

post_install() {
	systemctl enable waydroid-container.service
	load_profile
}

# Waydroid's container manager (waydroid-container.service) keeps the code it started with: the
# patches of a new version (the mounts of a session, ~/Android) only count once it starts again.
# Without an Android running that happens right away; while one runs (its container RUNNING or
# FROZEN), a transient unit waits until it has stopped, looking once a minute. A boot does it too.
WAITER='while :; do
	case $(lxc-info -P /var/lib/waydroid/lxc -n waydroid -sH 2>/dev/null) in
	RUNNING | FROZEN) sleep 60 ;;
	*) exec systemctl try-restart waydroid-container.service ;;
	esac
done'

restart_container() {
	systemctl is-active -q waydroid-container.service 2>/dev/null || return 0
	case $(lxc-info -P /var/lib/waydroid/lxc -n waydroid -sH 2>/dev/null) in
	RUNNING | FROZEN)
		systemd-run -q --collect --unit=waydroid-plinius-restart \
			-p Description="Waydroid takes the new version once Android has stopped" \
			sh -c "$WAITER" 2>/dev/null || true
		echo "Waydroid uses the new version once Android has stopped" ;;
	*) systemctl try-restart waydroid-container.service 2>/dev/null || true ;;
	esac
}

post_upgrade() {
	if [ "$(vercmp "$2" 1.6.3-6)" -lt 0 ]; then
		systemctl enable waydroid-container.service
	fi
	load_profile
	restart_container
}

pre_remove() {
	systemctl disable waydroid-container.service
}
