#!/bin/bash
# run with sudo or as root

# Get the current numeric value of ACODEC (Extracts the first percentage value only)
CURRENT_ACODEC=$(amixer get 'ACODEC' | grep -o '[0-9]*%' | head -n 1)

# Define the file path for /usr/sbin/audio.sh
AUDIO_SH_PATH="/usr/sbin/audio.sh"
TMP_FILE=$(mktemp)

# Check if the file exists
if [ ! -f "$AUDIO_SH_PATH" ]; then
  echo "audio.sh not found in /usr/sbin. Exiting."
  exit 1
fi

# Flag to track whether PCM has been added
PCM_ADDED=false

# Read the file line by line, modify the ACODEC lines only, and write to tmp file
while IFS= read -r line; do
    if [[ $line == *"amixer -c 0 set 'ACODEC'"* ]]; then
        # Correctly format the ACODEC line with the new value
        echo "amixer -c 0 set 'ACODEC' '$CURRENT_ACODEC'" >> "$TMP_FILE"
        
        # Only add the PCM line if it's not already added
        if ! $PCM_ADDED && ! grep -q "amixer -c 0 set 'PCM'" "$AUDIO_SH_PATH"; then
            echo "amixer -c 0 set 'PCM' '100%'" >> "$TMP_FILE"
            PCM_ADDED=true
        fi
    else
        # Keep the other lines as they are
        echo "$line" >> "$TMP_FILE"
    fi
done < "$AUDIO_SH_PATH"

# Move tmp file to the original file
mv "$TMP_FILE" "$AUDIO_SH_PATH"

# Set the permissions of /usr/sbin/audio.sh to -rwxr--r--
chmod 744 "$AUDIO_SH_PATH"

echo "ACODEC and PCM settings have been updated in $AUDIO_SH_PATH"
