#!/usr/bin/env sh
# Assemble the GitHub Pages site into site/: the README as the write-up and the cube, voice
# and webcam examples built for the browser. `./scripts/site.sh [profile]`; the profile is
# `pages` (smallest, slow) by default, `web` for a quick look. Needs the wasm32 target,
# wasm-bindgen-cli, and wasm-opt from binaryen if it is on PATH. Serve the result with
# `python3 scripts/serve.py --https --dir site`.
set -eu
cd "$(dirname "$0")/.."
profile="${1:-pages}"
rm -rf site && mkdir -p site
cp README.md web/site.html site/ && mv site/site.html site/index.html
cp PLAN.md site/ 2>/dev/null || true
# The pages profile also rebuilds std with panics as plain traps and no file:line in them,
# which is another 6% off; that needs the nightly flags below and `rust-src`. RUSTFLAGS
# replaces the list in .cargo/config.toml, so the WebCodecs cfg is repeated here.
if [ "$profile" = pages ]; then
  export RUSTFLAGS="--cfg=web_sys_unstable_apis -Zunstable-options -Cpanic=immediate-abort -Zlocation-detail=none"
  set -- -Zbuild-std=std,panic_abort
else
  set --
fi
for example in cube voice webcam; do
  cargo build --profile "$profile" --example "$example" --target wasm32-unknown-unknown --no-default-features --features web-demo "$@"
  mkdir -p "site/$example"
  wasm-bindgen --target web --no-typescript --out-dir "site/$example" --out-name app \
    "target/wasm32-unknown-unknown/$profile/examples/$example.wasm"
  if command -v wasm-opt >/dev/null 2>&1; then
    # The features rustc's wasm32-unknown-unknown target emits, and no more: `--all-features`
    # let an old binaryen write value types browsers refuse.
    wasm-opt -Oz --enable-bulk-memory --enable-nontrapping-float-to-int --enable-reference-types \
      --enable-sign-ext --enable-mutable-globals --enable-multivalue \
      -o "site/$example/app_bg.wasm" "site/$example/app_bg.wasm"
  fi
  cp web/loader.js "site/$example/"
  size=$(wc -c < "site/$example/app_bg.wasm" | tr -d ' ')
  sed "s/EXAMPLE/$example/g; s/WASM_SIZE/$size/g" web/demo.html > "site/$example/index.html"
  cp "examples/$example.rs" "site/$example/source.rs"
done
touch site/.nojekyll
du -sh site/*/app_bg.wasm
