#!/bin/bash

BASE_DIR="${1:-.}"

AUDIO_EXTENSIONS=("mp3" "wav" "flac" "aac" "ogg" "wma" "m4a" "ape" "alac" "wv" "dsf")

create_playlist() {
    local dir="$1"
    local playlist_file="$dir/playlist.m3u"

    if find "$dir" -maxdepth 1 -type f -iname "*.cue" | grep -q .; then
        echo "В директории '$dir' найден .cue файл. Плейлист не будет создан."
        return
    fi

    audio_files=()
    for ext in "${AUDIO_EXTENSIONS[@]}"; do
        while IFS= read -r -d $'\0' file; do
            audio_files+=("$(basename "$file")")
        done < <(find "$dir" -maxdepth 1 -type f -iname "*.$ext" -print0)
    done

    if [ "${#audio_files[@]}" -gt 1 ]; then
        printf "%s\n" "${audio_files[@]}" | sort > "$playlist_file"
        echo "Создан плейлист: $playlist_file"
    fi
}

find "$BASE_DIR" -type d | while read -r dir; do
    create_playlist "$dir"
done
