#!/bin/bash

. faustpath
. faustoptflags
. usage.sh

#-------------------------------------------------------------------
# Wrapping resources
HTML_FOOTER=""
CODE_WRAPPER1=""
CODE_WRAPPER2=""
JS_WRAPPER=""
LINKS=""
SVG=""
EMCC="false"
POLY="false"
OPT="false"
EXPORT="false"
WORKLET="false"
OPTIONS="-ftz 2"

echoHelp()
{
    usage faust2webaudiowast "[options] <file.dsp>"
    echo "Compiles Faust programs to self-contained HTML pages with WASM"
    option
    option -poly
    option -opt "optimize the wasm module using Binaryen tools (https://github.com/WebAssembly/binaryen)"
    option -worklet "generates AudioWorklet compatible code"
    option -links "add links to source code and SVG diagrams in the generated HTML file"
    option -emcc "compile C++ generated code to wasm with Emscripten, otherwise the internal wasm backend is used"
    exit
}

if [ "$#" -eq 0 ]; then
    echo 'Please, provide a Faust file to process !'
    echo ''
    echoHelp
fi

#-------------------------------------------------------------------
# Analyze command arguments :
# faust options                 -> OPTIONS
# existing *.dsp files          -> FILES
#

for p in $@; do
    if [ $p = "-help" ] || [ $p = "-h" ]; then
       echoHelp
    elif [ $p = "-links" ]; then
        SVG="-svg"
        LINKS="<div style=\"text-align:center;height:20px\">
                <style>
                a:link {font-family:Arial; font-size:12px; color:#3D3C3A; text-decoration:none}
                a:visited {font-family:Arial; font-size:12px; color:#3D3C3A; text-decoration:none}
                a:hover {font-family:Arial; font-size:12px; color:white; text-decoration:none}
                </style>
            <a href=\"DSP.dsp\" target=\"_blank\">source</a>
            <a href=\"DSP-svg/process.svg\" target=\"_blank\">diagram</a>
            </div>"
        EXPORT_FOOTER=export-wrapper.html
        EXPORT="true"
    elif [ $p = "-poly" ]; then
        POLY="true"
    elif [ $p = "-opt" ]; then
        OPT="true"
    elif [ $p = "-worklet" ]; then
        WORKLET="true"
    elif [ $p = "-emcc" ]; then
        EMCC="true"
    elif [ ${p:0:1} = "-" ]; then
        OPTIONS="$OPTIONS $p"
    elif [[ -f "$p" ]]; then
        FILES="$FILES $p"
    else
        OPTIONS="$OPTIONS $p"
    fi
done

echo "Compiling with :" $OPTIONS

#-------------------------------------------------------------------
# Set the compilation wrapping files depending of the compilation options
#

if [ $POLY = "true" ]; then
    echo "The mixer32.wasm code is copied"
    cp $FAUSTARCH/webaudio/mixer32.wasm .
    if [ $EMCC = "true" ]; then
        echo "Compiled with 'emcc' in polyphonic mode"
        CODE_WRAPPER1=webaudio-asm-poly.cpp
        JS_WRAPPER=webaudio-wasm-poly-emcc.js
        HTML_FOOTER=webaudio-wasm-poly-footer.html
    else
        if [ $WORKLET = "true" ]; then
            echo "Compiled with 'wasm' backend in polyphonic and AudioWorklet mode"
            CODE_WRAPPER1=webaudio-poly-workletprocessor-standalone-wrapper.js
            HTML_FOOTER=webaudio-wasm-poly-worklet-footer.html
        else
            echo "Compiled with 'wasm' backend in polyphonic mode"
            CODE_WRAPPER1=webaudio-wasm-poly-standalone-wrapper.js
            HTML_FOOTER=webaudio-wasm-poly-footer.html
        fi
    fi
else
    if [ $EMCC = "true" ]; then
        echo "Compiled with 'emcc'"
        CODE_WRAPPER1=webaudio-asm.cpp
        JS_WRAPPER=webaudio-wasm-emcc.js
        HTML_FOOTER=webaudio-wasm-footer.html
    else
        if [ $WORKLET = "true" ]; then
            echo "Compiled with 'wasm' backend in AudioWorklet mode"
            CODE_WRAPPER1=webaudio-workletprocessor-standalone-wrapper.js
            CODE_WRAPPER2=webaudio-workletnode-standalone-wrapper.js
            HTML_FOOTER=webaudio-wasm-worklet-footer.html
        else
            echo "Compiled with 'wasm' backend"
            CODE_WRAPPER1=webaudio-wasm-standalone-wrapper.js
            HTML_FOOTER=webaudio-wasm-footer.html
        fi
    fi
fi

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

BINARIES=""

for f in $FILES; do
    name=$(basename "$f" .dsp)

    # compile the Faust DSP to C++ or wasm code
    if [ $EMCC = "true" ]; then
        faust $SVG -a $FAUSTARCH/webaudio/$CODE_WRAPPER1 -i -uim -cn $name $OPTIONS $f -o $name.cpp || exit
    else
        if [ $POLY = "true" ]; then
            faust -lang wast-e $SVG $OPTIONS $f -o $name.wast || exit
        else
            faust -lang wast $SVG $OPTIONS $f -o $name.wast || exit
        fi
        # wasm ==> wasm optimizations
        if [ $OPT = "true" ]; then
            echo "Optimize wasm module"
            wasm-as $name.wast -o $name-tmp.wasm
            wasm-opt $name-tmp.wasm -O3 -o $name.wasm
        else
            wasm-as $name.wast -o $name.wasm
        fi
    fi

    if [ $EMCC = "true" ]; then
        # prepare emcc compilation files
        if [ $POLY = "false" ]; then    EXPORTED="['_"$name"_constructor','_"$name"_destructor','_"$name"_init','_"$name"_getSampleRate','_"$name"_instanceInit','_"$name"_instanceConstants','_"$name"_instanceResetUserInterface','_"$name"_instanceClear','_"$name"_compute','_"$name"_getNumInputs','_"$name"_getNumOutputs','_"$name"_setParamValue','_"$name"_getParamValue','_"$name"_getJSON']"
        else        EXPORTED="['_"$name"_poly_constructor','_"$name"_poly_destructor','_"$name"_poly_init','_"$name"_poly_getSampleRate','_"$name"_poly_instanceInit','_"$name"_poly_instanceConstants','_"$name"_poly_instanceResetUserInterface','_"$name"_poly_instanceClear','_"$name"_poly_compute','_"$name"_poly_getNumInputs','_"$name"_poly_getNumOutputs','_"$name"_poly_setParamValue','_"$name"_poly_getParamValue','_"$name"_poly_getJSON','_"$name"_poly_keyOn','_"$name"_poly_keyOff','_"$name"_poly_allNotesOff','_"$name"_poly_ctrlChange','_"$name"_poly_pitchWheel']"
        fi
        # compile the C++ code to wasm
        emcc -O3 --memory-init-file 0 -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 $name.cpp --post-js $FAUSTARCH/webaudio/$JS_WRAPPER -o $name.js -s EXPORTED_FUNCTIONS=$EXPORTED || exit

        # remove intermediate C++ file
        rm $name.cpp
    fi

    #java -jar /usr/local/bin/yuicompressor-2.4.8.jar $name-temp1.js -o $name-temp1.js --charset utf-8

    # compose the self-contained HTML page
    echo "<html>" > $name-temp2.html
    echo "<head>" >> $name-temp2.html
    echo "<meta charset=\"UTF-8\">" >> $name-temp2.html
    echo "<style type=\"text/css\">" >> $name-temp2.html
    cat $FAUSTARCH/js/stylesheet.js >> $name-temp2.html
    echo "</style>" >> $name-temp2.html
    echo "<script type=\"text/javascript\">" >> $name-temp2.html
    cat $FAUSTARCH/js/jsscripts.js >> $name-temp2.html
    if [ $EMCC != "true" ]; then
        if [ $WORKLET = "true" ]; then
            cp $name.js $name-processor.js
            sed -e "s/mydsp/"$name"/g" $FAUSTARCH/webaudio/$CODE_WRAPPER1 >> $name-processor.js
            sed -e "s/mydsp/"$name"/g" $FAUSTARCH/webaudio/$CODE_WRAPPER2 >> $name.js
        else
            sed -e "s/mydsp/"$name"/g" $FAUSTARCH/webaudio/$CODE_WRAPPER1 >> $name.js
        fi
        sed -e "s/mydsp/"$name"/g" $name.js >> $name-temp2.html
    fi
    echo "</script>" >> $name-temp2.html
    echo "</head>" >> $name-temp2.html
    echo "<body>" >> $name-temp2.html
    echo $LINKS >> $name-temp2.html
    cat $FAUSTARCH/webaudio/$HTML_FOOTER >> $name-temp2.html
    if [ $EXPORT = "true" ] ; then
        cat $FAUSTARCH/webaudio/$EXPORT_FOOTER >> $name-temp2.html
    fi
    echo "</body>" >> $name-temp2.html
    echo "</html>" >> $name-temp2.html
    sed -e "s/DSP/"$name"/g" $name-temp2.html > $name.html

    rm -f $name.js $name.wast $name-tmp.wasm $name-temp2.html

    # collect binary file name
    if [ $WORKLET = "true" ]; then
        BINARIES="$BINARIES$name.html;$name.js;"
    else
        BINARIES="$BINARIES$name.html;$name.wasm;"
    fi

done

echo $BINARIES
