#!/bin/sh

# watch the airplay recorder directory. as each file appears, move it away
# with a sequence number then convert to mp3 and delete

cd ~/Music/

# force build a directory; no harm if it already exists
# find out how many m4a files already exist in it

mkdir mp3ish

cd ~/Music/Recorder

while true; do

   for FILE in *.m4a; do
       [ -f "$FILE" ] || break

       BASE=${FILE%'.m4a'}
       N=`find ../mp3ish/ -maxdepth 1 -print|grep "$BASE" |wc -l`
       if (( $N != 0 )); then
          NN=$( printf "%04d" "$N" )
       else
          NN=""
       fi
       MP3NAME="../mp3ish/${BASE} ${NN}.mp3"
       echo $MP3NAME
       
       ffmpeg -y -i "$FILE" -codec:a libmp3lame -q:a 0 "$MP3NAME">/tmp/ffmpeg.log 2>&1

       rm "$FILE"

    done

    sleep 45

done