#!/usr/bin/env bash
# Pre-compile step: run the directive codegen, build the Go client to WebAssembly,
# and stage the JS shim. Run the dev server instead (go run ./server) for hot
# reload; this script is for a one-off/production-style build. Run from anywhere.
set -euo pipefail

cd "$(dirname "$0")"

echo "==> Generating directive glue (//gowasm:page, //gowasm:layout, //gowasm:server)"
go run kjol/cmd/wasmgen ./app

echo "==> Compiling ./wasm to wwwroot/app.wasm (GOOS=js GOARCH=wasm)"
GOOS=js GOARCH=wasm go build -o wwwroot/app.wasm ./wasm

echo "==> Copying Go's wasm_exec.js shim into wwwroot/"
GOROOT="$(go env GOROOT)"
if [ -f "$GOROOT/lib/wasm/wasm_exec.js" ]; then
  cp "$GOROOT/lib/wasm/wasm_exec.js" wwwroot/wasm_exec.js   # Go >= 1.24
else
  cp "$GOROOT/misc/wasm/wasm_exec.js" wwwroot/wasm_exec.js  # Go <= 1.23
fi

echo "==> Done. Run the server with:  go run ./server"
echo "    then open http://localhost:8085"
