#!/bin/bash

# === Configuration ===
BITRATE="128k"
ALBUM="Quran"
COMMENT="goldenquran.org"
JOBS=10

export BITRATE ALBUM COMMENT

# Function to process one file
process_file() {
  file="$1"
  base="${file%.mp3}"
  tmpfile="${base}_tmp_cbr.mp3"

  # Get bitrates
  format_bitrate=$(ffprobe -v error -show_entries format=bit_rate -of default=nw=1:nk=1 "$file")
  stream_bitrate=$(ffprobe -v error -select_streams a:0 -show_entries stream=bit_rate -of csv=p=0 "$file")

  # Check for VBR
  if [[ "$format_bitrate" == "$stream_bitrate" ]]; then
    echo "Already CBR, skipping: $file"
    return
  fi

  # Extract original artist metadata
  artist=$(ffprobe -v error -show_entries format_tags=artist -of default=nw=1:nk=1 "$file")
  title=$(basename "$file" .mp3)

  echo "Converting & tagging (removing cover): $file"

  ffmpeg -y -i "$file" \
    -map 0:a:0 -codec:a libmp3lame -b:a "$BITRATE" -ar 44100 -ac 2 \
    -metadata album="$ALBUM" \
    -metadata comment="$COMMENT" \
    -metadata title="$title" \
    "$tmpfile"

  mv -f "$tmpfile" "$file"
}

export -f process_file

# Process all .mp3 files
find . -maxdepth 1 -type f -iname "*.mp3" > mp3_list.txt
TOTAL=$(wc -l < mp3_list.txt)

echo "🔄 Found $TOTAL MP3 files to check..."

cat mp3_list.txt | pv -l -s "$TOTAL" | parallel -j "$JOBS" --bar process_file {}

rm mp3_list.txt
echo "✅ All done."
