#1. `1` = Pure peak detection - catches all volume spikes
#2. `1.5` = Very fast attack time (1.5ms) - reacts immediately to loud sounds
#3. `400` = Long release time (400ms) - slowly returns to normal after volume reduction
#4. `30` = Very low threshold (-30dB) - catches even quiet sounds
#5. `20` = High compression ratio (20:1) - strongly limits volume peaks
#6. `1` = Sharp knee - makes compression more aggressive
#7. `24` = Maximum makeup gain (24dB) - boosts the overall volume after compression
#
#This means:
#
#- Loud sounds will be automatically reduced
#- Quiet sounds will be automatically boosted
#- Volume peaks will be limited to prevent sudden loud noises
#- The overall volume will be more consistent
#- It applies to ALL audio output on your system
#
#If you want to customize:
#
#- For less aggressive compression: reduce ratio (e.g., 10 instead of 20)
#- For more natural sound: increase knee (e.g., 3 instead of 1)
#- For less boosting: reduce makeup gain (e.g., 15 instead of 24)
#- For slower response: increase attack time (e.g., 10 instead of 1.5)

#!/bin/bash

# Save as setup_agc.sh

# Exit on any error
set -e

echo "Setting up ALSA AGC system..."

# Check if running as root
if [ "$EUID" -ne 0 ]; then 
    echo "Please run as root (use sudo)"
    exit 1
fi

echo "Installing required packages..."
apt update
apt install -y alsa-utils swh-plugins ladspa-sdk

echo "Checking LADSPA plugin..."
if [ ! -f "/usr/lib/ladspa/sc4_1882.so" ]; then
    echo "SC4 plugin not found after installation. Please check your package manager."
    exit 1
fi

echo "Setting plugin permissions..."
chmod +x /usr/lib/ladspa/sc4_1882.so

echo "Creating ALSA configuration..."
cat > /etc/asound.conf << 'EOL'
# Base device with format conversion
pcm.converted {
    type plug
    slave {
        pcm "hw:0,0"
        format S16_LE
        channels 2
        rate 48000
    }
}

# AGC configuration
pcm.!default {
    type ladspa
    slave.pcm "converted"
    path "/usr/lib/ladspa"
    plugins [
        {
            label sc4
            input {
                controls [ 1 1.5 400 -30 20 1 24 ]
            }
        }
    ]
}

ctl.!default {
    type hw
    card 0
}
EOL

echo "Restarting ALSA..."
/usr/sbin/alsactl kill rescan

echo "Testing configuration..."
if /usr/bin/aplay -l &> /dev/null; then
    echo "Sound card detected successfully"
else
    echo "Warning: Could not detect sound card"
    exit 1
fi

echo "Setup complete! Testing audio..."
echo "Note: Please test audio after script completes by running: aplay /usr/share/sounds/alsa/Front_Center.wav"

echo "
Installation completed!

The configuration uses maximum possible values for loudness:
- Fastest attack time (1.5ms)
- Maximum compression ratio (20:1)
- Lowest threshold (-30dB)
- Maximum makeup gain (24dB)

To test the configuration, run:
aplay /usr/share/sounds/alsa/Front_Center.wav

To uninstall:
rm /etc/asound.conf
apt remove --purge swh-plugins ladspa-sdk
alsactl kill rescan
"

