#!/bin/bash

TARGET_DIR="."

# Check if directory exists
if [[ ! -d "$TARGET_DIR" ]]; then
    echo "Error: $TARGET_DIR is missing. Where are the tunes?"
    exit 1
fi

echo "Initiating deep scan of current directory..."

# ==========================================
# PASS 1: Convert WAV to Compressed Stereo MP3
# ==========================================
echo "=== Phase 1: Converting WAV files ==="
find "$TARGET_DIR" -type f -name "*.wav" -print0 | while IFS= read -r -d '' f; do
    base="${f%.*}"
    echo "Processing: ${f##*/}"
    
    # Convert WAV to highly compressed Stereo MP3 (VBR 6)
    ffmpeg -i "$f" -codec:a libmp3lame -qscale:a 6 "${base}.mp3" -y -loglevel error < /dev/null

    if [[ $? -eq 0 ]]; then
        echo "   [SUCCESS] Reclaimed space from ${f##*/}"
        rm "$f"
    else
        echo "   [FAILED] Could not convert ${f##*/}. Keeping original WAV."
    fi
done

# ==========================================
# PASS 2: Compress Existing MP3 Files Further (Stereo)
# ==========================================
echo "=== Phase 2: Compressing existing MP3 files ==="
find "$TARGET_DIR" -type f -name "*.mp3" -print0 | while IFS= read -r -d '' f; do
    # Skip temporary files if the script was interrupted previously
    if [[ "$f" == *.tmp.mp3 ]]; then continue; fi

    base="${f%.*}"
    tmp="${base}.tmp.mp3"
    
    echo "Processing existing MP3: ${f##*/}"
    
    # Force re-encode existing MP3 to VBR 6 Stereo
    ffmpeg -i "$f" -codec:a libmp3lame -qscale:a 6 "$tmp" -y -loglevel error < /dev/null

    if [[ $? -eq 0 ]]; then
        mv "$tmp" "$f"
        echo "   [SUCCESS] Compressed ${f##*/}"
    else
        echo "   [FAILED] Could not optimize ${f##*/}. Keeping original MP3."
        rm -f "$tmp"
    fi
done

echo "------------------------------------------"
echo "Deep scan complete. Storage should be breathing easier now."
