#!/bin/bash
# Sox Splitter, split WAV files at silence points.
# Concept and Testing by Glen MacArthur, coded by Google Gemini 3.

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

HELP="Timing Guide:
• 0.20s: Drum hits (Slider: 20)
• 0.60s: Phrases (Slider: 60)
• 1.50s: Songs (Slider: 150)"

# Standalone scale is the most reliable UI in YAD
RAW_VAL=$(yad --title="SoX Silence Splitter" \
             --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=60 --min-value=1 --max-value=200 --step=1 \
             --button="OK:0" --button="Cancel:1")

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

# Clean the output (removes the trailing '|')
VAL=$(echo "$RAW_VAL" | tr -d '|')
DURATION=$(printf "%.2f" "$(echo "scale=2; $VAL/100" | bc)")

for item in "$@"; do
    if [ -d "$item" ]; then
        for f in "$item"/*.wav; do
            [ -f "$f" ] || continue
            sox -V3 "$f" "${f%.*}-split.wav" silence -l 1 0.1 -65d 1 "$DURATION" -65d : newfile : restart >> "$LOG" 2>&1
        done
    else
        sox -V3 "$item" "${item%.*}-split.wav" silence -l 1 0.1 -65d 1 "$DURATION" -65d : newfile : restart >> "$LOG" 2>&1
    fi
done

notify-send "Sox Splitter" "Splitting complete! ✅"