#!/usr/bin/with-contenv bash

DEVICES=$(find /dev/dri /dev/dvb /dev/vchiq /dev/vcsm /dev/vc-mem /dev/video1? -type c -print 2>/dev/null)

if hash nvidia-smi 2>/dev/null; then
    echo "Runtime detected"
    echo "GPU: $(nvidia-smi --query-gpu=name --format=csv,noheader)"
    echo "Capabilities: ${NVIDIA_DRIVER_CAPABILITIES} Devices: ${NVIDIA_VISIBLE_DEVICES}"
fi

for i in ${DEVICES}; do
    # Get the group ID and NAME (if exists) for the current device in the list
    DEVICE_GROUP_ID=$(stat -c '%g' "$i")
    DEVICE_GROUP_NAME=$(getent group "${DEVICE_GROUP_ID}" | awk -F: '{print $1}')

    # If group NAME doesn't exist, create it and assign it the group ID
    if [[ -z "${DEVICE_GROUP_NAME}" ]]; then
        DEVICE_GROUP_NAME="video${RANDOM}"
        groupadd -g "${DEVICE_GROUP_ID}" "${DEVICE_GROUP_NAME}"
    fi

    getent group "${DEVICE_GROUP_NAME}" | grep -q abc || usermod -a -G "${DEVICE_GROUP_NAME}" abc
done
