#!/bin/bash

source ~/Workshop/emsdk/emsdk_env.sh > /dev/null 2>/dev/null
emsdk activate 3.1.41 >/dev/null 2>/dev/null

function clean () {
    echo "Cleaning..."
    rm -rf Build
    rm -f Code/{libecl.a,wecl.js,wecl.wasm}
    rm -f Code/wasm-ecl/wecl.*
}

function build () {
    echo "Building..."
    cp wecl.c wecl.lisp wasm-ecl/
    pushd wasm-ecl
    emcc -O2 \
         -sASYNCIFY -sASYNCIFY_STACK_SIZE=1048576 \
         -sASYNCIFY_IMPORTS=[cl_eval,js_test,js_read] \
         -sSTACK_SIZE=1048576 \
         -sINITIAL_MEMORY=67108864 \
         -sERROR_ON_UNDEFINED_SYMBOLS=0 \
         -sEXPORTED_RUNTIME_METHODS=ccall,cwrap,stringToNewUTF8,UTF8ToString \
         -sEXPORTED_FUNCTIONS=_wecl_brrt \
         --embed-file "wecl.lisp" \
         libecl{,gc,gmp}.a wecl.c -I./ -o wecl.js
    popd
    cp wasm-ecl/libecl{,gc,gmp}.a wasm-ecl/wecl.js wasm-ecl/wecl.wasm .
}

function serve () {
    echo "Serving..."
    pushd App
    ecl --load "../webserver.lisp"
    popd
}
 
if [ "${1}" == "clean" ]; then
    clean
elif [ "${1}" == "serve" ]; then
    serve
elif [ "${1}" == "build" ]; then
    clean
    cp -r Code Build
    pushd Build
    build
    popd
    rm -rf App
    mkdir -p App
    cp Build/*.{css,html,js,wasm,lisp} App
else
    echo "Command '${1}' not found."
fi
