#!/bin/bash
# Comprehensive AMD GPU Performance Fix for Benchmarking

# Colors for output
RED='\033[0:31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== AMD RX 6900 XT Benchmark Performance Fix ===${NC}"
echo ""

# Find the AMD GPU
GPU_PATH=""
for card in /sys/class/drm/card[0-9]; do
    if [ -f "$card/device/power_dpm_force_performance_level" ]; then
        GPU_PATH="$card/device"
        GPU_CARD=$(basename $(dirname $GPU_PATH))
        break
    fi
done

if [ -z "$GPU_PATH" ]; then
    echo -e "${RED}ERROR: Could not find AMD GPU!${NC}"
    exit 1
fi

echo -e "${GREEN}Found GPU at: $GPU_PATH${NC}"
echo ""

# Show current state
echo "=== BEFORE ==="
echo "Performance Level: $(cat $GPU_PATH/power_dpm_force_performance_level)"
echo "Core Clock:"
cat $GPU_PATH/pp_dpm_sclk | grep "\*"
echo "Memory Clock:"
cat $GPU_PATH/pp_dpm_mclk | grep "\*"
echo ""

# Apply fixes
echo -e "${YELLOW}Applying performance fixes...${NC}"

# 1. Set performance level to high
echo "high" | sudo tee $GPU_PATH/power_dpm_force_performance_level > /dev/null
echo "✓ Set performance level to HIGH"

# 2. Force highest core clock
echo "2" | sudo tee $GPU_PATH/pp_dpm_sclk > /dev/null
echo "✓ Forced highest core clock (2600MHz)"

# 3. Force highest memory clock  
echo "3" | sudo tee $GPU_PATH/pp_dpm_mclk > /dev/null
echo "✓ Forced highest memory clock (2000MHz effective)"

# 4. Set power limit to maximum if available
if [ -f "$GPU_PATH/hwmon/hwmon*/power1_cap_max" ]; then
    MAX_POWER=$(cat $GPU_PATH/hwmon/hwmon*/power1_cap_max)
    echo "$MAX_POWER" | sudo tee $GPU_PATH/hwmon/hwmon*/power1_cap > /dev/null 2>&1
    echo "✓ Set power limit to maximum"
fi

echo ""
echo "=== AFTER ===" 
echo "Performance Level: $(cat $GPU_PATH/power_dpm_force_performance_level)"
echo "Core Clock:"
cat $GPU_PATH/pp_dpm_sclk | grep "\*"
echo "Memory Clock:"
cat $GPU_PATH/pp_dpm_mclk | grep "\*"
echo ""

echo -e "${GREEN}GPU is now at maximum performance!${NC}"
echo ""
echo -e "${YELLOW}Additional tips:${NC}"
echo "1. Close all background applications"
echo "2. Make sure Sway compositor isn't limiting FPS"
echo "3. Run benchmark in fullscreen mode"
echo "4. Check CPU governor is set to 'performance'"
echo ""
echo "To check CPU governor:"
echo "  cat /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor | head -1"
echo ""
echo "To set CPU to performance mode:"
echo "  echo performance | sudo tee /sys/devices/system/cpu/cpu*/cpufreq/scaling_governor"
echo ""
echo -e "${GREEN}Now run your benchmark!${NC}"
