#!/bin/sh -eu
# shellcheck disable=SC1091
[ -e /lxc-ci/etc/config ] && . /lxc-ci/etc/config

if [ "${DAILY_REBOOT:-}" != "true" ]; then
    exit 0
fi

# Avoid restarting all machines at the same time, so wait up to 1.5h
sleep "$(shuf -i1-90 -n1)"m

while :; do
    # Check that nothing is running
    # shellcheck disable=SC2010
    if [ -n "$(incus list -cn -fcsv status=running)" ]; then
        sleep 1m
        continue
    fi

    # Make sure there's nothing about to start
    sleep 1m

    # shellcheck disable=SC2010
    if [ -n "$(incus list -cn -fcsv status=running)" ]; then
        sleep 1m
        continue
    fi

    reboot
    exit 0
done
