#!/bin/bash
# Sox Normalize, normalize the volume of selected Audio Files.
# Concept and Testing by Glen MacArthur, coded by Google Gemini 3.

LOG="$HOME/.avl-mxe-file-action.log"
: > "$LOG"

if [ $# -eq 0 ]; then
    echo "No files received." >> "$LOG"
    exit 1
fi

# 1. YAD Dialog with Instructional Text
DATA=$(yad --title="Sox Normalize" \
    --image="/usr/local/share/icons/custom/sox-app.png" \
    --window-icon="/usr/local/share/icons/custom/sox.png" \
    --form \
    --text="<b>Normalization Guide:</b>\n\
• <b>0.0 to 0.1:</b> Maximum volume (Standard for final files)\n\
• <b>1.0 to 3.0:</b> Safe headroom for further mixing/processing\n\
• <b>6.0+:</b> Quiet (Useful for background loops or samples)\n\n\
<i>Higher values = Lower peak volume.</i>" \
    --field="Target Peak Level (dB below 0):NUM" "0.1!0..20!0.1!1" \
    --button="OK:0" --button="Cancel:1" --width=450)

[ $? -ne 0 ] && exit 1

# Extract value
TARGET=$(echo "$DATA" | cut -d'|' -f1)

# Ensure the value is negative for the 'norm' effect
NORM_VAL=$(echo "-$TARGET" | sed 's/--/-/')

echo "--- Sox Normalize to ${NORM_VAL}dB Started: $(date) ---" > "$LOG"

# 2. Processing Loop
for item in "$@"; do
    [[ "$item" == "bash" ]] && continue

    process_file() {
        local input="$1"
        local output="${input%.*}-norm.wav"
        
        # 'norm' searches for the peak and scales the file
        sox -V3 "$input" "$output" norm "$NORM_VAL" >> "$LOG" 2>&1
    }

    if [ -d "$item" ]; then
        for f in "$item"/*.wav; do
            [ -f "$f" ] && process_file "$f"
        done
    elif [ -f "$item" ]; then
        process_file "$item"
    fi
done

notify-send "Sox Normalize" "Normalized to ${NORM_VAL} dB! ✅"
 

