#!/bin/bash
# Burn-in of all GPUs at once: gpu_burn + a CSV row per card every 5 s + a temperature watchdog.
# Usage: ./burn4.sh <seconds>   (expects ./gpu-burn/gpu_burn next to this script: https://github.com/wilicc/gpu-burn)
SECS=${1:-300}
cd "$(dirname "$0")" || exit 1
TS=$(date +%H%M%S)
CSV=burn4-$TS.csv
LOG=burn4-$TS.log
MAXT=88
echo "time,gpu,temp,memtemp,power,util,sm_clock,mem_used,throttle" > "$CSV"
( cd gpu-burn && ./gpu_burn -tc "$SECS" ) > "$LOG" 2>&1 &
BP=$!
while kill -0 $BP 2>/dev/null; do
  now=$(date +%H:%M:%S)
  nvidia-smi --query-gpu=index,temperature.gpu,temperature.memory,power.draw,utilization.gpu,clocks.sm,memory.used,clocks_throttle_reasons.active --format=csv,noheader,nounits \
    | sed "s/^/$now,/; s/, /,/g" >> "$CSV"
  hot=$(nvidia-smi --query-gpu=temperature.gpu --format=csv,noheader,nounits | sort -n | tail -1)
  if [ "$hot" -ge "$MAXT" ]; then
    echo "$now WATCHDOG: temp $hot >= $MAXT, killing gpu_burn" | tee -a "$LOG"
    pkill -x gpu_burn
  fi
  sleep 5
done
wait $BP
echo "=== summary $CSV ==="
awk -F, 'NR>1{g=$2; if($3>t[g])t[g]=$3; if($4>m[g])m[g]=$4; p[g]+=$5; n[g]++; if($9!~/^0x0+$/ && $6>0)th[g]++}
END{for(g in n)printf "GPU%s: max temp %d C, max mem %d C, avg power %.0f W, throttled %d/%d\n",g,t[g],m[g],p[g]/n[g],th[g]+0,n[g]}' "$CSV" | sort
grep -c WATCHDOG "$LOG"
tail -n 12 "$LOG" | tr '\r' '\n' | grep -vE '^\s*$' | tail -n 10
