#!/bin/sh
set -e

# Verify the toolkit configuration handling. None of these steps require an
# NVIDIA GPU, so they run inside a GPU-less LXD container.

CONFIG=/etc/nvidia-container-runtime/config.toml

# The maintainer scripts (postinst) run "nvidia-ctk config --in-place" on
# configure, so the default config file must exist after installation.
echo "Checking that ${CONFIG} was created on install"
test -f "${CONFIG}"

# It must be parseable TOML with the expected top-level table.
grep -q '^\[nvidia-container-cli\]' "${CONFIG}"

# "nvidia-ctk config default" prints a valid default configuration to stdout.
echo "Checking 'nvidia-ctk config default'"
out="$(nvidia-ctk config default)"
echo "${out}" | grep -q 'nvidia-container-cli'

# Running the in-place update again must be idempotent: the file content does
# not change on a second invocation.
echo "Checking that 'nvidia-ctk config --in-place' is idempotent"
before="$(sha256sum "${CONFIG}")"
nvidia-ctk --quiet config --config-file="${CONFIG}" --in-place
after="$(sha256sum "${CONFIG}")"
if [ "${before}" != "${after}" ]; then
    echo "ERROR: config file changed after a no-op in-place update" >&2
    exit 1
fi

# Setting a value with --set is reflected in a freshly generated config.
echo "Checking 'nvidia-ctk config --set'"
tmpcfg="$(mktemp)"
nvidia-ctk --quiet config --set accept-nvidia-visible-devices-as-volume-mounts=true --output="${tmpcfg}"
grep -qE '^accept-nvidia-visible-devices-as-volume-mounts[[:space:]]*=[[:space:]]*true' "${tmpcfg}"
rm -f "${tmpcfg}"
