#!/bin/bash

# Get metadata from first mp3 file if it exists
first_file=$(ls *.mp3 2>/dev/null | head -n 1)

if [ -n "$first_file" ]; then
    default_artist=$(ffprobe -v quiet -show_entries format_tags=artist -of default=noprint_wrappers=1:nokey=1 "$first_file")
    default_album=$(ffprobe -v quiet -show_entries format_tags=album -of default=noprint_wrappers=1:nokey=1 "$first_file")
    default_date=$(ffprobe -v quiet -show_entries format_tags=date -of default=noprint_wrappers=1:nokey=1 "$first_file")
    default_composer=$(ffprobe -v quiet -show_entries format_tags=composer -of default=noprint_wrappers=1:nokey=1 "$first_file")
fi

# Prompt with defaults
read -p "Enter Album Artist [$default_artist]: " album_artist
album_artist=${album_artist:-$default_artist}

read -p "Enter Album [$default_album]: " album
album=${album:-$default_album}

read -p "Enter Release Date (YYYY or YYYY-MM-DD) [$default_date]: " release_date
release_date=${release_date:-$default_date}

read -p "Enter Composer [$default_composer]: " composer
composer=${composer:-$default_composer}

echo ""
echo "Retagging files..."
echo "Album Artist: $album_artist"
echo "Album: $album"
echo "Release Date: $release_date"
echo "Composer: $composer"
echo ""

for file in *.mp3; do
    filename="${file%.*}"
    track_num=$(echo "$filename" | grep -oP '^\d+')
    
    echo "Retagging: $file (Track $track_num)"
    
    if [ -n "$composer" ]; then
        ffmpeg -i "$file" -c copy \
          -metadata title="$filename" \
          -metadata track="$track_num" \
          -metadata album_artist="$album_artist" \
          -metadata artist="$album_artist" \
          -metadata album="$album" \
          -metadata date="$release_date" \
          -metadata composer="$composer" \
          -metadata disc="" \
          -metadata discnumber="" \
          -metadata totaldiscs="" \
          -metadata disk="" \
          -metadata disknumber="" \
          "${filename}_temp.mp3" 2>/dev/null
    else
        ffmpeg -i "$file" -c copy \
          -metadata title="$filename" \
          -metadata track="$track_num" \
          -metadata album_artist="$album_artist" \
          -metadata artist="$album_artist" \
          -metadata album="$album" \
          -metadata date="$release_date" \
          -metadata composer="" \
          -metadata disc="" \
          -metadata discnumber="" \
          -metadata totaldiscs="" \
          -metadata disk="" \
          -metadata disknumber="" \
          "${filename}_temp.mp3" 2>/dev/null
    fi
    
    mv "${filename}_temp.mp3" "$file"
done

echo ""
echo "Done! All files retagged."
