#Compiles emscripten instance of this project for the web. Use "full" argument if your PGE has to be completely rebuilt. Use "headless" argument for a headless version.
#C++
output=$(dpkg -l | grep libx11-dev)
if [[ -z $output ]]
then
    sudo apt install libx11-dev libpulse-dev mesa-common-dev libpng-dev libstdc++-12-dev
fi
if [[ "$1" == "full" || "$2" == "full" ]]; then
    rm "pixelGameEngine_wasm.o"
fi
source ../emsdk/emsdk_env.sh
if [ ! -f "pixelGameEngine_wasm.o" ]
then
    printf "Pixel Game Engine compile object missing. Compiling for the first time..."
    em++ -std=c++20 -O2 ${EMSCRIPTEN_CUSTOM_PARAMS} -s ALLOW_MEMORY_GROWTH=1 -s MAXIMUM_MEMORY=4GB -s MAX_WEBGL_VERSION=2 -s MIN_WEBGL_VERSION=2 -s USE_SDL_MIXER=2 -s USE_LIBPNG=1 -c pixelGameEngine.cpp -o pixelGameEngine_wasm.o
fi
if [ -d "assets" ]; then
    em++ -std=c++20 -O2 ${EMSCRIPTEN_CUSTOM_PARAMS} -s ALLOW_MEMORY_GROWTH=1 -s MAXIMUM_MEMORY=4GB -s MAX_WEBGL_VERSION=2 -s MIN_WEBGL_VERSION=2 -s USE_SDL_MIXER=2 -s USE_LIBPNG=1 $(find . -type f -name "*.cpp" -not -path "./test/*" -not -name "pixelGameEngine.cpp") pixelGameEngine_wasm.o -o ${PROJECT_NAME}.html --preload-file ./assets
else
    em++ -std=c++20 -O2 ${EMSCRIPTEN_CUSTOM_PARAMS} -s ALLOW_MEMORY_GROWTH=1 -s MAXIMUM_MEMORY=4GB -s MAX_WEBGL_VERSION=2 -s MIN_WEBGL_VERSION=2 -s USE_SDL_MIXER=2 -s USE_LIBPNG=1 $(find . -type f -name "*.cpp" -not -path "./test/*" -not -name "pixelGameEngine.cpp") pixelGameEngine_wasm.o -o ${PROJECT_NAME}.html
fi

cp buildtemplate.html ${PROJECT_NAME}.html
sed -i "s/_REPLACEME_/$PROJECT_NAME.js/" ${PROJECT_NAME}.html

if [[ "$1" == "headless" || "$2" == "headless" ]]; then
    echo "Running as headless web server"
    emrun --no_browser ${PROJECT_NAME}.html
else
    emrun --serve_after_close ${PROJECT_NAME}.html
fi

if [ $? -eq 127 ]
then
    echo "Failed to find Emscripten. Running install script."
    PWD=$(pwd)
    cd ..
    git clone https://github.com/emscripten-core/emsdk.git
    cd emsdk
    git pull
    ./emsdk install latest
    ./emsdk activate latest
    source ./emsdk_env.sh
    cd $PWD
    echo "Emscripten has been installed. Try running the command again."
fi