#!/usr/bin/env bash

set -e

PROJECTS_FOLDER=~/music-projects/Rendered-Projects

# file separator (needed to handle files with spaces)
IFS="
"

function info_log(){
    echo -n ">>> [ "
    echo -n $@
    echo " ]"
}

function run_ffmpeg(){
    local input=$1
    local output=$2

    info_log "ffmpeg : ${output}"
    ffmpeg \
        -i "${input}" \
        -f mp3 \
        -codec:a libmp3lame \
        -qscale:a 5 \
        -ar 44100 \
        -loglevel error \
        -af loudnorm \
        "${output}"


}

function delete(){
    local input=$1

    if [[ -e "${input}" ]]
    then
        info_log "delete : ${input}"
        rm "${input}"
    fi
}

for file in `ls ${PROJECTS_FOLDER} | grep wav$`
do
    filename=`basename ${file} .wav`
    mp3="${filename}.mp3"

    info_log ${filename}

    delete "${PROJECTS_FOLDER}/${mp3}"
    run_ffmpeg "${PROJECTS_FOLDER}/${file}" "${PROJECTS_FOLDER}/${mp3}"
    delete "${PROJECTS_FOLDER}/${file}"

done