#!/bin/bash
# SoxCDBurn, a simple terminal-based CD Burner using Wodim.
# Concept and Testing by Glen MacArthur, coded by Google Gemini 3.

# 1. Identify Target
if [ -d "$1" ]; then
    cd "$1"
    # Use nullglob to prevent literal strings if no files match
    shopt -s nullglob
    FILES=( *.{wav,flac,mp3,m4a} )
    shopt -u nullglob
else
    FILES=("$@")
fi

# Ensure we actually have files to process
if [ ${#FILES[@]} -eq 0 ]; then
    yad --error --text="No valid audio files found." --center
    exit 1
fi

# 2. Calculate Total Duration
TOTAL_SECONDS=0
for f in "${FILES[@]}"; do
    # Ensure the file exists before probing
    if [ -f "$f" ]; then
        DURATION=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$f")
        # Add to total using bc with scale to handle decimals
        TOTAL_SECONDS=$(echo "$TOTAL_SECONDS + $DURATION" | bc -l)
    fi
done

# 3. Capacity & Confirmation
# Calculate minutes for display (rounding up)
TOTAL_MINUTES=$(echo "scale=0; ($TOTAL_SECONDS + 59) / 60" | bc -l)

if (( $(echo "$TOTAL_SECONDS > 4800" | bc -l) )); then
    yad --error --text="<b>Disc Over Limit!</b>\n\nTotal duration: $TOTAL_MINUTES mins.\nA standard CD only holds 80 mins." --width=300 --center
    exit 1
fi

# Use -v to ensure variable expansion in YAD text
yad --question --title="Quick Audio CD Burner" \
    --text="<b>Ready to burn?</b>\n\nTotal Duration: ${TOTAL_MINUTES} minutes\nSource: $(basename "$PWD")" \
    --width=450 --image="/usr/local/share/icons/custom/burner-app.png" \
    --window-icon="/usr/local/share/icons/custom/burner.png" \
    --button="Burn CD":0 --button="Cancel":1 --center || exit 1

# 4. The Processing Loop
TEMP_CD=$(mktemp -d)
TRACK_LIST=$(mktemp)

# Write the full paths of the files to a temp list
for f in "${FILES[@]}"; do
    echo "$f" >> "$TRACK_LIST"
done

# Pass the temp file path to terminology
terminology -T="Normalizing and Burning CD" -e bash -c "echo 'Normalizing and Resampling for Red Book Spec...'; \
count=1; \
while IFS= read -r f; do \
    echo \"Processing Track \$count: \$(basename \"\$f\")\"; \
    sox \"\$f\" -r 44100 -c 2 -b 16 \"$TEMP_CD/track_\$(printf %02d \$count).wav\" norm -1; \
    ((count++)); \
done < \"$TRACK_LIST\"; \
echo -e '\n--- Preparation Complete ---'; \
echo 'Please insert a blank CD-R...'; \
wodim -v -audio -pad -dao dev=/dev/sr0 \"$TEMP_CD\"/*.wav; \
echo -e '\nBurn Complete! Ejecting...'; \
rm -f \"$TRACK_LIST\"; \
eject /dev/sr0; read -n 1"

rm -rf "$TEMP_CD"