#!/bin/bash

#####################################################################
#                                                                   #
#               Compiles Faust programs to impulse tests			#
#               (c) Grame, 2016                                     #
#                                                                   #
#####################################################################

#-------------------------------------------------------------------
# Set Faust include path

if [ -f $FAUST_LIB_PATH/music.lib ]
    then
    FAUSTLIB=$FAUST_LIB_PATH
elif [ -f /usr/local/share/faust/all.lib ]
    then
    FAUSTLIB=/usr/local/share/faust/
elif [ -f /usr/share/faust/all.lib ]
    then
    FAUSTLIB=/usr/share/faust/
else
    echo "ERROR : $0 cannot find Faust library dir (usually /usr/local/share/faust)"
fi

for p in $@; do
    if [ ${p:0:1} = "-" ]; then
        OPTIONS="$OPTIONS $p"
    elif [[ -f "$p" ]]; then
        FILES="$FILES $p"
    else
        OPTIONS="$OPTIONS $p"
    fi
done

#-------------------------------------------------------------------
# compile the *.dsp files 

for f in $FILES; do

    name=$(basename "$f" .dsp)
    name_exp=$name"_exp"
    dirname=$(dirname "$f");

    # compile Faust to asm.js
    faust -e "$f" -o $name_exp".dsp"
    cp $FAUSTLIB/webaudio/asm-node-wrapper-double.js "${f%.dsp}.js"

	# run the binary to generate the impulse response
    cd $dirname
    sed -e "s/SOURCE_FILE/"$name_exp"/g" "$name.js" >> "$name-tmp1.js"
    sed -e "s/DSP_NAME/"$name"/g" "$name-tmp1.js" >> "$name-tmp2.js"
    node "$name-tmp2.js" || exit

    # cleanup
    rm "$name.js" "$name-tmp1.js" "$name-tmp2.js" "$name_exp.dsp"

done

