#!/bin/bash
# Stress the GPU with a real Vulkan compute workload and monitor clocks
H=/sys/class/drm/card0/device/hwmon/hwmon1
SYSFS=/sys/class/drm/card0/device

echo "=== PRE-LOAD ==="
echo "FREQ: $(cat $H/freq1_input) Hz"
cat $SYSFS/pp_dpm_sclk

# Check if pp_table exists or can be created
echo "=== PP_TABLE CHECK ==="
ls -la $SYSFS/pp_table 2>/dev/null || echo "pp_table: NOT PRESENT"
sudo cat $SYSFS/pp_table 2>/dev/null | wc -c || echo "pp_table: NOT READABLE"

# Create a Vulkan compute stress with vkcube or glmark if available
if command -v vkcube &>/dev/null; then
  echo "Starting vkcube..."
  timeout 8 vkcube --c 99999 &>/dev/null &
  STRESS_PID=$!
elif command -v glmark2-es2 &>/dev/null; then
  echo "Starting glmark2..."
  timeout 8 glmark2-es2 --off-screen &>/dev/null &
  STRESS_PID=$!
else
  # Fallback: just do heavy memory operations via python
  echo "Starting python GPU mem stress..."
  timeout 8 python3 -c "
import ctypes, time
# Just allocate and fill memory rapidly to force GPU activity
data = bytearray(512*1024*1024)
for i in range(100):
    data[i*1024:(i+1)*1024] = b'x' * 1024
time.sleep(6)
" &>/dev/null &
  STRESS_PID=$!
fi

# Monitor during load
for i in 1 2 3 4 5 6; do
  sleep 1
  freq=$(cat $H/freq1_input)
  dpm=$(cat $SYSFS/pp_dpm_sclk | grep '\*')
  power=$(cat $H/power1_input)
  temp=$(cat $H/temp1_input)
  echo "t+${i}s: freq=${freq}Hz dpm=${dpm} power=${power}uW temp=${temp}mC"
done

kill $STRESS_PID 2>/dev/null
wait $STRESS_PID 2>/dev/null

echo "=== POST LOAD ==="
sleep 1
echo "FREQ: $(cat $H/freq1_input) Hz"
cat $SYSFS/pp_dpm_sclk

# Check if we can write pp_table
echo "=== PP_TABLE WRITE TEST ==="
if [ -f "$SYSFS/pp_table" ]; then
  echo "pp_table exists, trying to read..."
  sudo cat $SYSFS/pp_table > /tmp/pp_table_backup.bin 2>/dev/null
  echo "Read $(wc -c < /tmp/pp_table_backup.bin) bytes"
else
  echo "No pp_table file — cannot modify power table"
fi
