#! /bin/bash -e

#####################################################################
#                                                                   #
#               Compiles Faust programs to Max externals			#
#				using single precision samples						#
#               (c) Grame, 2012                                     #
#                                                                   #
#####################################################################

. faustpath
. faustoptflags

CXXFLAGS=$MYGCCFLAGS
CXXFLAGS+=" -fbracket-depth=512"

NVOICES=-1
EFFECT=""

# path to max SDK

SDK=/usr/local/include/c74support/
MAXINC=$SDK/max-includes
MSPINC=$SDK/msp-includes

createInfoPList() {
	(
	echo '<?xml version="1.0" encoding="UTF-8"?>'
	echo '<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">'
	echo '<plist version="1.0">'
	echo '<dict>'
	echo '	<key>CFBundleExecutable</key>'
	echo "	<string>$1</string>"
	echo '	<key>CFBundleName</key>'
	echo "	<string>$1</string>"
	echo '	<key>CFBundlePackageType</key>'
	echo '	<string>iLaX</string>'
	echo '</dict>'
	echo '</plist>'
	) > "$2"
}

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

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

#-------------------------------------------------------------------
# Analyze command arguments :
# faust options                 -> OPTIONS
# if -omp : -openmp or -fopenmp -> OPENMP
# existing *.dsp files          -> FILES
#

#PHASE 2 : dispatch command arguments
while [ $1 ]
do
    p=$1

    if [ $p = "-help" ] || [ $p = "-h" ]; then
        echo "faust2msp [-nvoices <num>] [-effect <effect.dsp>] [-midi] <file.dsp>"
        echo "Use '-nvoices <num>' to produce a polyphonic self-contained DSP with <num> voices, ready to be used with MIDI"
        echo "Use '-effect <effect.dsp>' to produce a polyphonic DSP connected to a global output effect, ready to be used with MIDI"
        echo "Use '-midi' to activate MIDI control"
        exit
    fi

    if [ "$p" = -omp ]; then
        if [[ $CXX == "icpc" ]]; then
            OMP="-openmp"
        else
            OMP="-fopenmp"
        fi
    fi
  
    if [ "$p" = -icc ]; then
    	ignore=" "
    elif [ $p = "-nvoices" ]; then
        shift
        NVOICES=$1
        if [ $NVOICES -ge 0 ]; then
            CXXFLAGS="$CXXFLAGS -DNVOICES=$NVOICES"
        fi
    elif [ $p = "-effect" ]; then
        POLYDEFS="-DPOLY2"
        shift
    EFFECT=$1
    elif [ $p = "-midi" ]; then
        MIDIDEFS="-DMIDICTRL"
    elif [ ${p:0:1} = "-" ]; then
	    OPTIONS="$OPTIONS $p"
	elif [[ -f "$p" ]]; then
	    FILES="$FILES $p"
	else
	    OPTIONS="$OPTIONS $p"        
	fi

shift

done

#-------------------------------------------------------------------
# Check darwin specifics
#
if [[ $(uname) == Darwin ]]; then
    EXT="~.mxo"
fi

#-------------------------------------------------------------------
# compile the *.dsp files
#
PATH=$PATH:/usr/local/bin

for p in $FILES; do

    CC=g++

    CUR=$(pwd)
    f=$(basename "$p")
	SRCDIR=$(dirname "$p")

    # creates a temporary dir 
    TDR=$(mktemp -d faust.XXXXXX)
	TMP="$TDR/${f%.dsp}"
    mkdir "$TMP"

    # compile faust to c++
    if [ "$EFFECT" = "" ]; then
        faust -i -a $FAUSTLIB/max-msp/max-msp.cpp $OPTIONS "$SRCDIR/$f" -o "$TMP/${f%.dsp}.cpp" || exit
    else
        faust -i -a $FAUSTLIB/max-msp/max-msp.cpp $OPTIONS "$SRCDIR/$f" -o "$TMP/${f%.dsp}.cpp" || exit
        faust -i -cn effect -a $FAUSTLIB/minimal-effect.cpp "$SRCDIR/$EFFECT" -o "$TMP/effect.cpp" || exit
    fi

    # compile c++ to binary
    (
	cd "$TMP"
	install -d "${f%.dsp}$EXT/Contents/MacOS"
	#$CC $CXXFLAGS -mmacosx-version-min=10.7 -Wfatal-errors -framework Carbon $POLYDEFS $MIDIDEFS -I ../../ -I$MAXINC -I$MSPINC $FAUSTTOOLSFLAGS -F$MAXINC -F$MSPINC -framework MaxAPI -framework MaxAudioAPI `pkg-config --cflags --static --libs sndfile` -arch i386 -Wl,-Y,1455 -bundle "${f%.dsp}.cpp" -o "${f%.dsp}$EXT/Contents/MacOS/${f%.dsp}~"
    $CC $CXXFLAGS -mmacosx-version-min=10.7 -Wfatal-errors -framework Carbon $POLYDEFS $MIDIDEFS -I ../../ -I$MAXINC -I$MSPINC $FAUSTTOOLSFLAGS -F$MAXINC -F$MSPINC -framework MaxAPI -framework MaxAudioAPI -arch i386 -Wl,-Y,1455 -bundle "${f%.dsp}.cpp" -o "${f%.dsp}$EXT/Contents/MacOS/${f%.dsp}~"
    ) >/dev/null  || exit

    rm -rf "$SRCDIR/${f%.dsp}$EXT"

    # Keep .dsp and .cpp files in the plug-in
    cp "$TMP/${f%.dsp}.cpp" "$TMP/${f%.dsp}$EXT"   
    cp "$SRCDIR/$f" "$TMP/${f%.dsp}$EXT"

    cp -r "$TMP/${f%.dsp}$EXT" "$SRCDIR/${f%.dsp}$EXT"
    rm -rf "$TDR"

    # collect binary file name for FaustWorks
    BINARIES="$BINARIES$SRCDIR/${f%.dsp}$EXT;"
    
done

BINARIES="$BINARIES ui.js"

echo $BINARIES


