#!/usr/bin/env bash
set -euo pipefail

TARGET=$1
NAME="$(basename "${TARGET}")"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
DIST="${REPO_ROOT}/dist/${TARGET}"
PROFILE="wasm-release"
RUST_TARGET="wasm32-unknown-unknown"
BUILD_FLAGS="--profile ${PROFILE} --target ${RUST_TARGET} --features engine/web"

if [[ "${TARGET}" == prototypes/* ]]; then
    BUILD_DIR="${REPO_ROOT}/prototypes"
    BUILD_FLAGS="${BUILD_FLAGS} --bin ${NAME}"
else
    BUILD_DIR="${REPO_ROOT}/${TARGET}"
fi

# Build
(cd "${BUILD_DIR}" && cargo build ${BUILD_FLAGS})

WASM="${CARGO_TARGET_DIR}/${RUST_TARGET}/${PROFILE}/${NAME}.wasm"

# wasm-bindgen
mkdir -p "${DIST}"

# Cleanup
rm -rf ${DIST}/*.wasm ${DIST}/*.js ${DIST}/*.html

wasm-bindgen \
    --no-typescript \
    --target web \
    --out-dir "${DIST}" \
    --out-name "bin" \
    "${WASM}"

# wasm-opt size pass.
# Enable the wasm features rustc/wasm-bindgen emit (bulk-memory etc.) so
# validation passes, and strip debug/producers sections for size.
wasm-opt -Oz \
    --strip-debug --strip-producers \
    --enable-bulk-memory \
    --enable-nontrapping-float-to-int \
    --enable-sign-ext \
    --enable-reference-types \
    --enable-mutable-globals \
    --enable-multivalue \
    -o "${DIST}/bin_bg-tmp.wasm" \
    "${DIST}/bin_bg.wasm"
mv "${DIST}/bin_bg-tmp.wasm" "${DIST}/bin_bg.wasm"

# HTML template
cp "${REPO_ROOT}/web/index.html" "${DIST}/index.html"

# Assets
if [[ "${TARGET}" == prototypes/* ]]; then
    ASSETS_SRC="${REPO_ROOT}/prototypes/assets/${NAME}"
else
    ASSETS_SRC="${REPO_ROOT}/${TARGET}/assets"
fi
ASSETS_DST="${DIST}/assets"

if [[ -d "${ASSETS_SRC}" ]]; then
    mkdir -p "$(dirname "${ASSETS_DST}")"
    rm -rf "${ASSETS_DST}"
    cp -r "${ASSETS_SRC}" "${ASSETS_DST}"
fi
