#!/usr/bin/env bash
set -euo pipefail

pids=()

running=$(/usr/bin/nvidia-smi pmon -c 1 | grep -v Xorg | awk '{print $1}')
for i in $(seq 1 $1); do
  if echo $running | grep -v $((i-1)); then
    echo "Running test on available GPU: $((i-1))"
    CUDA_VISIBLE_DEVICES=$((i-1)) dockergpu --runtime=nvidia infra.docker.zooxlabs.com/check_gpu_health_image:1.0 &
    pids[${i}]=$!
  fi
done

if [ ${#pids[@]} -gt 0 ]; then
  for pid in ${pids[*]}; do
    wait $pid
  done
fi
