#!/bin/sh
# Build Kobo Deluxe as a WebAssembly app via Emscripten.
#
# Prereq: install and activate emsdk so emcmake / emcc are on PATH.
#   git clone https://github.com/emscripten-core/emsdk ~/emsdk
#   ~/emsdk/emsdk install latest && ~/emsdk/emsdk activate latest
#   . ~/emsdk/emsdk_env.sh
#
# Output: build-web/kobodl.{html,js,wasm,data}
# Serve from build-web/ with any static server that sets the COOP/COEP headers
# required for SharedArrayBuffer (pthreads). Example:
#   ./build-web.sh && ./build-web.sh serve

set -e

HERE="$(cd "$(dirname "$0")" && pwd)"
BUILD="$HERE/build-web"

case "${1:-build}" in
    serve)
        cd "$BUILD"
        exec python3 -c "
import http.server, socketserver
class H(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Cross-Origin-Opener-Policy', 'same-origin')
        self.send_header('Cross-Origin-Embedder-Policy', 'require-corp')
        super().end_headers()
socketserver.TCPServer(('', 8000), H).serve_forever()
"
        ;;
    clean)
        rm -rf "$BUILD"
        ;;
    build|*)
        command -v emcmake >/dev/null 2>&1 || {
            echo "emcmake not found. Source emsdk_env.sh first." >&2
            exit 1
        }
        mkdir -p "$BUILD"
        cd "$BUILD"
        emcmake cmake -DCMAKE_BUILD_TYPE=Release "$HERE"
        cmake --build . -j
        echo
        echo "Built: $BUILD/index.html"
        echo "Serve: ./build-web.sh serve  (then open http://localhost:8000/)"
        ;;
esac
