#!/usr/bin/env bash
# RaveOS Safe GPU Performance Optimizer & Stutter Preventer
# Prevents P-state lock lag, Wayland compositor micro-stuttering, and thermal throttling drops.

set -euo pipefail

# Root check
if [[ $EUID -ne 0 ]]; then
   echo "[RaveOS-GPU] Error: Root permissions required." >&2
   exit 1
fi

log() {
  echo "[RaveOS-GPU] $1"
}

# 1. AMD GPU Optimization (Auto P-State + Smooth Power Cap)
optimize_amd() {
  log "Optimizing AMD GPU acceleration without P-state locking..."
  for card in /sys/class/drm/card*/device; do
    if [ -f "$card/power_dpm_force_performance_level" ]; then
      # Use 'auto' instead of rigid 'high' to prevent mouse lag and compositor stutter
      echo "auto" > "$card/power_dpm_force_performance_level" 2>/dev/null || true
    fi
  done
}

# 2. NVIDIA GPU Optimization (Adaptive PowerMizer + Smooth TDP Limit)
optimize_nvidia() {
  if command -v nvidia-smi &>/dev/null; then
    log "Optimizing NVIDIA GPU (Adaptive PowerMizer mode)..."
    # Auto-boost enabled, avoiding forced clock lock that breaks PCIe ASPM
    nvidia-smi --auto-boost-default=ENABLED 2>/dev/null || true
    
    if command -v nvidia-settings &>/dev/null && [ -n "${DISPLAY:-}" ]; then
      # Set PowerMizer to Auto/Adaptive (0) instead of max performance (1) to prevent compositor stutter
      nvidia-settings -a "[gpu:0]/GpuPowerMizerMode=0" 2>/dev/null || true
    fi
  fi
}

# Main Execution
main() {
  log "Starting safe GPU optimization..."
  
  if lspci | grep -iE "vga|3d|display" | grep -i "amd" &>/dev/null; then
    optimize_amd
  fi
  
  if lspci | grep -iE "vga|3d|display" | grep -i "nvidia" &>/dev/null; then
    optimize_nvidia
  fi
  
  log "GPU Optimization complete. Dynamic P-states and ASPM preserved."
}

main "$@"
