#!/bin/sh

function BuildPlaylist() {
	section="$1"; basePath="$2"; relPath="$3"; outFile="$4"

	if [ -z "$basePath" ]; then echo "BasePath missing in section $section."; break; fi
	if [ -z "$relPath" ]; then echo "RelPath missing in section $section."; break; fi
	if [ -z "$outFile" ]; then echo "OutFile missing in section $section."; break; fi

	if [ ! -d "$basePath" ]; then echo "BasePath $basePath does not exist in section $section."; break; fi
	if [ ! -d "$basePath/$RelPath" ]; then echo "RelPath $3 does not exist in section $section."; break; fi

	pushd $basePath > /dev/null
	find $relPath/ -name '*.mp3'|sort -R > $outFile
	popd > /dev/null
}

function ParseINI() {
	inFile="$1"
	callback="$2"
	shift 2
	params="$*"

  if [ ! -f "$inFile" ]; then echo "File $inFile not found!"; exit; fi

	local IFS="="

	# Am Ende eine leere Section anhängen, damit auch der letzte Abschnitt verarbeitet wird
	echo "[]"|cat "$inFile" -|sed 's/\t/ /g;s/^ \+//;s/ \+$//;/^#/d;/^$/d'|while read name value; do
		[ -z "$name" ] && continue

		local IFS=" "
		if [ "${name:0:1}" == "[" ]; then
			[ -z "$section" ] || eval $callback $section ${sectionParams[*]}
			section=${name/'['/}
			section=${section/']'/}
			unset sectionParams
		else
			counter=0
			for param in $params; do
				if [ "$param" == "$name" ]; then
					sectionParams[$counter]="'$value'"
				fi
				let counter++
			done
		fi
		local IFS="="
	done
}

ParseINI "/etc/genplaylist.conf" "BuildPlaylist" "BasePath" "RelPath" "OutFile"

