#!/bin/bash

IFS=$'\t\n'

### Konfiguration: ###

Playlists="/mnt/archive/cont/Audio Music/0 Playlists"
MediaHome="/mnt/archive/cont/Audio Music"
GenreVerzArray=("2 Albums by Genre" "4 Videos")
Bilder="/home/ernstlx/.scripts/raise-genres/icons"
Ext=.m3u
Titelzahl=50
AltHome="../.."
StoreStr='^Stored'

######################

### Anfangswert für $RANDOM ###
# RANDOM=$(date +%s)

### Titelzahl = ARGUMENT, wenn vorhanden
if [ $1 ]; then
    Titelzahl=$1
fi

### Playlists-Verzeichnis leeren, wenn befüllt ###
if [ -d "${Playlists}" ] && [ "$(ls ${Playlists})" ]; then
    for pl in $(ls ${Playlists}); do
        if [ -d "$Playlists/$pl" ] && [[ ! $pl =~ $StoreStr ]]; then
            rm -r $Playlists/$pl
        fi
    done
    if [ -f "${Bilder}/$(basename $Playlists).jpg" ]; then
        cp "${Bilder}/$(basename $Playlists).jpg" "${Playlists}/folder.jpg"
    fi
elif [ ! -d "${Playlists}" ]; then
    echo "Fehler: Verzeichnis ${Playlists} nicht gefunden!"
    exit 1
fi

### Playlists für jedes Genre erzeugen ###
for genreverz in ${GenreVerzArray[@]}; do
    echo "Erzeuge Playlists für ${genreverz}:"
    mkdir $Playlists/$genreverz
    if [ -f "${Bilder}/${genreverz}.jpg" ]; then
        cp "${Bilder}/${genreverz}.jpg" "${Playlists}/${genreverz}/folder.jpg"
    fi
    Pool=()
    for gen in $(ls -d ${MediaHome}/${genreverz}/.*); do
        if [ -f "$gen" ]; then
            Pool=(`cat $gen | grep -v °.`)
            Genre=$(basename $gen)
            Genre="${Genre: 1}${Ext}"
            echo $Genre
            if [ ${#Pool[@]} -lt $Titelzahl ]; then
                max=${#Pool[@]}
            else
                max=$Titelzahl
            fi
            i=0
            contr=()
            while [ $i -lt $max ]; do
                nr=$((`od -An -N2 -i /dev/urandom`%${#Pool[@]}))
                if [ ! ${contr[$nr]} ]; then
                    if [ "$AltHome" ]; then
                      echo "${AltHome}/${Pool[$nr]}" >> $Playlists/$genreverz/$Genre
                    else
                      echo "${MediaHome}/${Pool[$nr]}" >> $Playlists/$genreverz/$Genre
                    fi
                    contr[$nr]=1
                    ((i+=1))
                fi
            done
        fi
    done
done
exit 0
