#!/bin/bash -e

#####################################################################
#                                                                   #
#                    faust2audiokit generator                       #
#                       (c) Grame, 2021                             #
#                                                                   #
#####################################################################

. faustpath
. faustoptflags
. usage.sh

CXXFLAGS+=" $MYGCCFLAGS"  # So that additional CXXFLAGS can be used

ARCHFILE1=$FAUSTARCH/audiokit/FaustDSP.mm
ARCHFILE2=$FAUSTARCH/audiokit/SwiftGenerator.cpp

# exit if a command fails
set -e

# global option variables
NVOICES=0
MIDI=false

echoHelp ()
{
    echo "faust2audiokit [-midi] [-nvoices <num>] [additional Faust options (-vec -vs 8...)] <file.dsp>"
    option
    options -midi
    option "-nvoices <num>"
    echo ""
}

###########################
# Processing Arguments
###########################

while [ $1 ]
do
    p=$1
    # help
    if [ $p = "-help" ] || [ $p = "-h" ]; then
        echoHelp
        exit 0
    # -nvoices:
    elif [ $p = "-nvoices" ]; then
        shift
        NVOICES=$1
    # -midi
    elif [ $p = "-midi" ]; then
        MIDI=true
    elif [[ -f "$p" ]]; then
        FILE="$p"
    # other compile options
    else
        OPTIONS="$OPTIONS $p"
    fi

shift
done

if [ -z $FILE ]; then
    echo "Please, provide a Faust file to process"
    exit 1
fi

###########################
# Compile the *.dsp files
###########################

for p in $FILE; do
    CUR=$(pwd)
    f=$(basename "$p")
    SRCDIR=$(dirname "$p")
    
    # creates the dir 
    dspName="${f%.dsp}"
    rm -rf "$SRCDIR/$dspName"
    mkdir "$SRCDIR/$dspName"
    
    # compile faust to c++
    faust -uim -i -cn $dspName -a $ARCHFILE1 $OPTIONS $f -o "$SRCDIR/$dspName/FaustDSP.mm" || exit
    faust -i -a $ARCHFILE2  $f -o "$SRCDIR/$dspName/faust2swift.cpp" || exit
    
    # for MIDI
    if [ $MIDI == true ]; then
        echo "#define MIDICTRL" | cat - "$SRCDIR/$dspName/FaustDSP.mm" > temp && mv temp "$SRCDIR/$dspName/FaustDSP.mm"
    fi
    # for POLY
    if [ "$NVOICES" -gt "0" ]; then
        echo "#define POLY" | cat - "$SRCDIR/$dspName/FaustDSP.mm" > temp && mv temp "$SRCDIR/$dspName/FaustDSP.mm"
        echo "#define NVOICES $NVOICES" | cat - "$SRCDIR/$dspName/FaustDSP.mm" > temp && mv temp "$SRCDIR/$dspName/FaustDSP.mm"
    fi

 	# create Swift wrapper
    (
    	cd "$SRCDIR/$dspName" && c++ -std=c++11 -O3 faust2swift.cpp -o faust2swift && ./faust2swift && rm faust2swift faust2swift.cpp
    ) > /dev/null || exit

    # create the source folder
    echo "Create the $SRCDIR/$dspName folder"
    
done
