#!/bin/bash

# Prompt for source directory to search for audio files
read -p "Enter the source directory to search for audio files: " source_dir

# Prompt for directory where audio files will be saved
read -p "Enter the directory to store audio files: " dest_dir

# Ask the user if they want to maintain the original folder structure
while true; do
    read -p "Do you want to maintain the original folder structure? (y/n): " maintain_structure
    case "$maintain_structure" in
        [yY]) maintain_structure="y"; break ;;
        [nN]) maintain_structure="n"; break ;;
        *) echo "Invalid input. Please enter 'y' for Yes or 'n' for No." ;;
    esac
done

# Create the destination directory if it doesn't exist
mkdir -p "$dest_dir" 2>/dev/null

# Display a message indicating that the copying process has started
echo "Copying Audio Files..."

# Initialize file counter
file_count=0

# Find all audio files with common extensions and process them
find "$source_dir" -type f \( \
    -iname "*.mp3" -o \
    -iname "*.wav" -o \
    -iname "*.m4a" -o \
    -iname "*.aac" -o \
    -iname "*.flac" -o \
    -iname "*.caf" -o \
    -iname "*.aiff" -o \
    -iname "*.aif" -o \
    -iname "*.ogg" -o \
    -iname "*.wma" -o \
    -iname "*.opus" -o \
    -iname "*.m4r" \
\) -exec bash -c '
    for file; do
        if [[ "$2" == "y" ]]; then
            # Preserve folder structure: recreate the directory path in the destination
            target_dir="$1/$(dirname "$file")"
            mkdir -p "$target_dir" 2>/dev/null
            target="$target_dir/$(basename "$file")"
        else
            # Single folder: place all files directly into the destination folder
            base_name=$(basename "$file")
            target="$1/$base_name"

            # Check for duplicates and add a suffix if needed
            count=1
            while [[ -e "$target" ]]; do
                target="$1/${base_name%.*}_$count.${base_name##*.}"
                ((count++))
            done
        fi

        # Copy the file to the determined target path
        cp "$file" "$target" 2>/dev/null

        # Update file count and print message every 100 files
        ((file_count++))
        if (( file_count % 100 == 0 )); then
            echo "$file_count files copied so far..."
        fi
    done
' bash "$dest_dir" "$maintain_structure" {} + 2>/dev/null

# Final completion message
echo "All audio files have been successfully copied to $dest_dir."