#!/bin/sh
set -e

# Exercise "nvidia-ctk runtime configure" against throw-away config files.
# This adds the NVIDIA runtime to a container engine's configuration and does
# not require an NVIDIA GPU, so it works inside a GPU-less LXD container.

WORK="$(mktemp -d)"
trap 'rm -rf "${WORK}"' EXIT

echo "Step 1"
# --- containerd -----------------------------------------------------------
# For containerd the NVIDIA runtime configuration is written to a drop-in file
# rather than the main config. Point both at the throw-away directory so the
# test never touches the system-wide /etc/containerd location.
ctd_cfg="${WORK}/containerd.toml"
ctd_dropin="${WORK}/conf.d/nvidia.toml"
: > "${ctd_cfg}"
echo "Configuring containerd (drop-in at ${ctd_dropin})"
nvidia-ctk runtime configure \
    --runtime=containerd \
    --config="${ctd_cfg}" \
    --drop-in-config="${ctd_dropin}" \
    --config-source=file \
    --quiet
grep -q 'nvidia' "${ctd_dropin}"

echo "Step 2"
# A dry-run must not create the drop-in file on disk.
echo "Checking containerd --dry-run does not write the drop-in"
rm -rf "${WORK}/conf.d"
nvidia-ctk runtime configure \
    --runtime=containerd \
    --config="${ctd_cfg}" \
    --drop-in-config="${ctd_dropin}" \
    --config-source=file \
    --dry-run \
    --quiet
if [ -e "${ctd_dropin}" ]; then
    echo "ERROR: --dry-run created the containerd drop-in file" >&2
    exit 1
fi

echo "Step 3"
# --- docker ---------------------------------------------------------------
docker_cfg="${WORK}/daemon.json"
echo '{}' > "${docker_cfg}"
echo "Configuring docker at ${docker_cfg}"
nvidia-ctk runtime configure \
    --runtime=docker \
    --config="${docker_cfg}" \
    --quiet

grep -q 'nvidia' "${docker_cfg}"

echo "Step 4"
# Setting the NVIDIA runtime as default is reflected in the docker config.
echo '{}' > "${docker_cfg}"
nvidia-ctk runtime configure \
    --runtime=docker \
    --config="${docker_cfg}" \
    --nvidia-set-as-default \
    --quiet
grep -q 'default-runtime' "${docker_cfg}"
grep -q 'nvidia' "${docker_cfg}"
