#!/usr/bin/env sh
set -ou pipefail

# Generates playlists for all mp3 and flac files in a directory, ignoring itself in the "parent" folder

PLAYLIST_FOLDER="/home/default/Music/playlists/mpd"     # Playlist folder for mpd
PREFIX="music/playlists"                                # relative links to add to playlists, based on mpd virtual file structure
EXTENSIONS=("mp3" "opus" "flac" "m4a" "mkv" "webm")

# Disable nullglob and set pattern matching to fix spaces
shopt -s nullglob
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")

cd $PLAYLIST_FOLDER || { echo "Could not cd into PLAYLIST_FOLDER"; exit 1; }
parent=`basename $PWD`

# Delete old generated playlists
if [[ -f "*.gen.m3u" ]]; then
    rm *.gen.m3u
fi
if [[ -f ".trackNames" ]]; then
    rm .trackNames
fi

# For all playlist directories to generate
for playlistDir in ../*; do
    if [[ -d "$playlistDir" ]] && [[ "$playlistDir" != "../$parent" ]]; then
	# playlist filename needed for mpd
    playlist=`echo "$playlistDir" | sed "s/^\.\.\///g"`
	# escaped version of filename needed for bash
    escaped=`printf '%q\n' "$playlist"`

    # echo "playlist=$playlist"
    # echo "escaped=$escaped"  

	# touch file
    > "$playlist.gen.m3u"
        
	# write all files with newlines
    > .track-names

    for EXT in ${EXTENSIONS[@]}; do
        # echo `find "../$playlist" -mindepth 1 -type f -name "*.$EXT" -printf x | wc -c`
        if [[ `find "../$playlist" -mindepth 1 -type f -name "*.$EXT" -printf x | wc -c` != 0 ]]; then
            ls -1 ../$escaped/*.$EXT >> .track-names 2> /dev/null
            # echo `ls -1 ../$playlist/*.$EXT >> 2> /dev/null`
        fi
    done
   
    # echo `cat .track-names` 
    cat .track-names | while IFS="" read -r song || [ -n "$song" ] ; do
        unprefixed=`echo "$song" | sed "s/^\.\.\///g"`
        # echo "$PREFIX/$unprefixed"
        echo "$PREFIX/$unprefixed" >> "$playlist.gen.m3u"
    done < .track-names
    
    if [[ -f ".track-names" ]]; then
        rm .track-names
    fi
fi
done

IFS=$SAVEIFS
