#!/bin/dash -ue

### BEGIN INIT INFO
# Short-Description:    System containers startup/shutdown
# Description:          System containers startup/shutdown
# Provides:             incus-startup
# Required-Start:       incus
# Required-Stop:        incus
# Default-Start:        2 3 4 5
# Default-Stop:         0 1 6
### END INIT INFO

# WARNING:
# This script has not been tested on hosts with cgroup v1.
# The host system must have a cgroup v2 hierarchy mounted.

# Under runit-init the incus service already handles this,
# so we exit immediately if incus runit service is enabled
if [ -f /etc/runit/stopit ] && [ -e /etc/service/incus ]; then
    exit 0
fi

DESC='System containers startup/shutdown'
NAME=incus-startup

# Import log_* functions.
. /lib/lsb/init-functions

case "${1:-}" in
    start)
        printf '%s' "Starting ${DESC}: ${NAME}"
        if [ -x /usr/libexec/incus/incusd ] && /usr/libexec/incus/incusd activateifneeded > /dev/null 2>&1; then
            log_success_msg
        else
            log_failure_msg
            exit 1
        fi

        exit 0
        ;;
    stop)
        printf '%s' "Stopping ${DESC}: ${NAME}"
        if [ -x /usr/libexec/incus/shutdown ] && /usr/libexec/incus/shutdown > /dev/null 2>&1; then
            log_success_msg
        else
            log_failure_msg
            exit 1
        fi

        exit 0
        ;;
    status)
        echo "There is no long-running daemon for this service, so there is no status."
        exit 0
    ;;
    restart|force-reload)
        "$0" stop
        exec "$0" start
        ;;
    *)
        printf '%s\n' "Usage: $0 {start|stop|restart|force-reload}" 1>&2
        exit 1
        ;;
esac
