#!/bin/bash
# Sox Trimmer, trim silence from the beginning and end of a WAV file.
# Concept and Testing by Glen MacArthur, coded by Google Gemini 3

LOG="$HOME/.avl-mxe-file-action.log"
echo "--- Trimmer Started: $(date) ---" > "$LOG"

HELP="Sensitivity Guide:
• 30: Aggressive (Noisy files)
• 50: Standard (Vocals)
• 80: Sensitive (Clean tracks)"

THRESHOLD=$(yad --title="SoX Silence Trimmer" \
                --image="/usr/local/share/icons/custom/sox-app.png" \
                --window-icon="/usr/local/share/icons/custom/sox.png" \
                --center --width=400 \
                --text="$HELP" \
                --scale --value=65 --min-value=30 --max-value=80 --step=1 \
                --button="OK:0" --button="Cancel:1")

[[ $? -ne 0 ]] && exit 1

# Clean the output
DB=$(echo "$THRESHOLD" | tr -d '|')

for item in "$@"; do
    if [ -d "$item" ]; then
        for f in "$item"/*.wav; do
            [ -f "$f" ] || continue
            sox -V3 "$f" "${f%.*}-trimmed.wav" silence 1 0.1 -${DB}d >> "$LOG" 2>&1
            mv "${f%.*}-trimmed.wav" "$f"
        done
    else
        sox -V3 "$item" "${item%.*}-trimmed.wav" silence 1 0.1 -${DB}d >> "$LOG" 2>&1
        mv "${item%.*}-trimmed.wav" "$item"
    fi
done

notify-send "Sox Trimmer" "Trimming complete! ✅"