#!/bin/bash

# Ask for the thumbnail filename
echo "=== Album Art Embedder (Recursive) ==="
echo "Current directory: $(pwd)"
read -p "Enter thumbnail filename in this directory (e.g., cover.jpg): " thumbnail

# Full path to thumbnail
thumbnail_path="$(pwd)/$thumbnail"

# Check if thumbnail exists
if [ ! -f "$thumbnail_path" ]; then
    echo "Error: Thumbnail not found at $thumbnail_path"
    exit 1
fi

# Ask for album artist
read -p "Enter album artist name: " album_artist

# Get album name from current directory
album_name="$(basename "$(pwd)")"

echo ""
echo "Found thumbnail: $thumbnail_path"
echo "Album: $album_name"
echo "Album Artist: $album_artist"
echo "Processing all mp3/mp4 files in subdirectories..."
echo ""

# Counter for processed files
count=0

# Find all mp3 and mp4 files in subdirectories (not current dir)
find . -mindepth 2 -type f \( -name "*.mp3" -o -name "*.mp4" \) | while read -r file; do
    echo "Processing: $file"
    
    # Get file extension
    ext="${file##*.}"
    
    # Create temporary filename
    temp_file="${file}.tmp.${ext}"
    
    # Add thumbnail and metadata using ffmpeg
    if [ "$ext" = "mp3" ]; then
        ffmpeg -i "$file" -i "$thumbnail_path" \
               -map 0 -map 1 \
               -c copy \
               -metadata album_artist="$album_artist" \
               -metadata album="$album_name" \
               -disposition:v:0 attached_pic \
               "$temp_file" 2>/dev/null
    else
        # For mp4 files
        ffmpeg -i "$file" -i "$thumbnail_path" \
               -map 0 -map 1 \
               -c copy \
               -metadata artist="$album_artist" \
               -metadata album="$album_name" \
               -disposition:v:0 attached_pic \
               "$temp_file" 2>/dev/null
    fi
    
    if [ $? -eq 0 ]; then
        mv "$temp_file" "$file"
        ((count++))
        echo "✓ Done"
    else
        echo "✗ Failed"
        [ -f "$temp_file" ] && rm "$temp_file"
    fi
    echo ""
done

echo "Finished! Processed $count files."
echo "Album Artist set to: $album_artist"
echo "Album set to: $album_name"
