#!/bin/sh


cd "$1"


MyPath="$HOME/Desktop/Audio/"$(basename "$(dirname "$1")")"/${PWD##*/}"


mkdir -p "$MyPath"


if [ "$2" = "ALAC" ]; then
	ls *flac | while read f; do "$(dirname "$0")/ffmpeg" -i "$f" -acodec alac  "$MyPath/$(basename "${f/.flac}").m4a" > /dev/null & done
else
	ls *flac | while read f;do "$(dirname "$0")/ffmpeg" -i "$f" -c:a aac -b:a $2 "$MyPath/$(basename "${f/.flac}").m4a" > /dev/null & done
fi;



# wait for spawned ffmpeg processes to finish
while ps axg | grep -vw grep | grep -w ffmpeg > /dev/null; do sleep 1; done



# copy cover art to local folder
cd "$MyPath"
cp "$1"/cover.jpg cover.jpg
cp "$1"/folder.jpg cover.jpg

# make files with cover art
for f in *.m4a; do "$(dirname "$0")/AtomicParsley" "$f" --artwork cover.jpg; done; 
# remove files without cover art
find . -type f -not -name '*temp*' -print0 | xargs -0 rm --
# rename files with cover art
for f in *.m4a; do g=${f//-temp*./.}; mv "$f" "$g"; done;


exit 0
