#!/bin/sh
#
# incus		System container and virtual machine manager
#
# chkconfig:	345 20 80
#
# description:	Incus is a system container and virtual machine manager \
#		built on LXC and QEMU, with a REST API and the incus CLI.
# processname:	incusd
# pidfile:	/var/run/incusd.pid
#

# Source function library
. /etc/rc.d/init.d/functions

# Get network config
. /etc/sysconfig/network

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network -a "$1" != stop -a "$1" != status ]; then
		msg_network_down "Incus"
		exit 1
	fi
else
	exit 0
fi

# Get service config - may override defaults
[ -f /etc/sysconfig/incus ] && . /etc/sysconfig/incus

pidfile="/var/run/incusd.pid"
incusd="/usr/libexec/incus/incusd"
wrapper="/usr/libexec/incus/incus-wrapper"

start() {
	if [ -f /var/lock/subsys/incus ]; then
		msg_already_running "Incus"
		return
	fi

	# lxcfs makes /proc inside containers reflect their cgroup limits
	if [ -x /etc/rc.d/init.d/lxcfs ] && [ ! -f /var/lock/subsys/lxcfs ]; then
		/etc/rc.d/init.d/lxcfs start
	fi

	msg_starting "Incus"
	daemon --makepid --pidfile $pidfile --waitforname incusd \
		$wrapper --group incus-admin $OPTIONS
	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then
		show "Waiting for Incus to become ready"
		busy
		if $incusd waitready --timeout=600; then
			ok
			touch /var/lock/subsys/incus
		else
			fail
			RETVAL=1
		fi
	fi
}

stop() {
	if [ ! -f /var/lock/subsys/incus ]; then
		msg_not_running "Incus"
		return
	fi

	# Stop daemons.
	msg_stopping "Incus"
	# stops all instances, then the daemon; the API call returns before the process is gone
	$incusd shutdown --timeout=600
	for i in $(seq 1 30); do
		status --pidfile $pidfile incusd incus >/dev/null 2>&1 || break
		sleep 1
	done
	if status --pidfile $pidfile incusd incus >/dev/null 2>&1; then
		killproc --pidfile $pidfile incusd
	else
		ok
	fi
	rm -f /var/lock/subsys/incus $pidfile
}

condrestart() {
	if [ ! -f /var/lock/subsys/incus ]; then
		msg_not_running "Incus"
		RETVAL=$1
		return
	fi

	stop
	start
}

RETVAL=0
# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  restart)
	stop
	start
	;;
  try-restart)
	condrestart 0
	;;
  force-reload)
	condrestart 7
	;;
  status)
	status --pidfile $pidfile incusd incus
	RETVAL=$?
	;;
  *)
	msg_usage "$0 {start|stop|restart|try-restart|force-reload|status}"
	exit 3
esac

exit $RETVAL
