#!/bin/sh
set -e

# Verify that the systemd units shipped by nvidia-container-toolkit-base are
# installed and become active, and that they are still active after a reboot.
#
# These units do not require an NVIDIA GPU: nvidia-cdi-refresh.path watches for
# driver/toolkit changes and triggers nvidia-cdi-refresh.service. On a GPU-less
# machine (such as an LXD container/VM) the .service is gated by an
# ExecCondition and is not expected to run, but the .path unit must still be
# enabled and active.

PATH_UNIT="nvidia-cdi-refresh.path"
SERVICE_UNIT="nvidia-cdi-refresh.service"

check_units_present() {
    echo "I: ${PATH_UNIT} is installed"
    systemctl cat "${PATH_UNIT}" >/dev/null

    echo "I: ${SERVICE_UNIT} is installed"
    systemctl cat "${SERVICE_UNIT}" >/dev/null
}

check_path_active() {
    echo "I: ${PATH_UNIT} is enabled"
    systemctl is-enabled "${PATH_UNIT}"

    echo "I: ${PATH_UNIT} is active"
    systemctl is-active "${PATH_UNIT}"
}

if [ -z "${AUTOPKGTEST_REBOOT_MARK:-}" ]; then
    check_units_present
    check_path_active

    echo "I: rebooting to confirm the path unit starts on boot"
    /tmp/autopkgtest-reboot rebooted
fi

if [ "${AUTOPKGTEST_REBOOT_MARK:-}" = "rebooted" ]; then
    echo "I: system came back up after reboot"
    check_units_present

    echo "I: ${PATH_UNIT} is active again after reboot"
    check_path_active

    echo "I: ${SERVICE_UNIT} did not fail on a GPU-less machine"
    # The service is gated by an ExecCondition; on hardware without an NVIDIA
    # driver it should be skipped rather than failing.
    if systemctl is-failed --quiet "${SERVICE_UNIT}"; then
        echo "E: ${SERVICE_UNIT} is in a failed state" >&2
        systemctl status "${SERVICE_UNIT}" --no-pager || true
        exit 1
    fi
fi

echo "OK"
