#!/sbin/openrc-run

command="/usr/sbin/lxd"
command_args="${LXD_OPTIONS}"
command_background="true"
pidfile="/run/${RC_SVCNAME}.pid"
retry="${LXD_TIMEOUT:-60}"
extra_started_commands="quit"
description_quit="Daemon quits and leaves the instances running"

: ${LXD_FORCE_STOP:="no"}

depend() {
	need net cgroups dbus
	use lxcfs
	after firewall
}

start_pre() {
	# Required for running systemd containers
	if [ -d /sys/fs/cgroup/unified ] && ! [ -d /sys/fs/cgroup/systemd ]; then
		checkpath --directory --owner root:lxd /sys/fs/cgroup/systemd
		mount -t cgroup \
			-o rw,nosuid,nodev,noexec,relatime,none,name=systemd \
			cgroup /sys/fs/cgroup/systemd
	fi
}

stop() {
	ebegin "Stopping ${RC_SVCNAME}"
	if [ "$LXD_FORCE_STOP" = "no" ]; then
		$command shutdown --timeout ${LXD_TIMEOUT:-60}
	elif [ "$LXD_FORCE_STOP" = "yes" ]; then
		$command shutdown --force
	fi
}

quit() {
	ebegin "Quitting ${RC_SVCNAME}"
	start-stop-daemon --signal SIGQUIT --pidfile $pidfile --quiet
	rm /run/openrc/started/lxd
}
