#!/usr/bin/env bash
# Assemble dist/ — the CSP-clean static build served at learn.bztmon.com.
#
# The artifact build inlines GSAP and the app JS because the artifact CSP blocks every
# external request. nginx has no such constraint, so here they stay SEPARATE files:
# `script-src 'self'` holds with no 'unsafe-inline' exception, and the two GSAP bundles
# (116KB, unchanged between deploys) become independently cacheable.
set -euo pipefail
IFS=$'\n\t'

trap 'printf "build failed at line %s\n" "$LINENO" >&2' ERR

here="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
cd -- "$here"

dist="$here/dist"
src_markup="ec2-part1.html"
src_app="ec2-part2.html"

for f in "$src_markup" "$src_app" gsap.min.js st.min.js; do
  [[ -f "$f" ]] || { printf 'missing source: %s\n' "$f" >&2; exit 1; }
done

rm -rf -- "$dist"
mkdir -p -- "$dist"

# --- app.js: strip the single <script> wrapper part2 carries -----------------
# part2 is exactly one <script>…</script> block; served standalone it must be raw JS.
sed -e '1{/^[[:space:]]*<script>[[:space:]]*$/d}' \
    -e '${/^[[:space:]]*<\/script>[[:space:]]*$/d}' \
    -- "$src_app" > "$dist/app.js"

if grep -qiE '</?script' -- "$dist/app.js"; then
  printf 'app.js still contains a script tag — the wrapper strip did not match\n' >&2
  exit 1
fi

# --- index.html: markup + external script refs -------------------------------
{
  cat -- "$src_markup"
  cat <<'HTML'

<script src="/gsap.min.js"></script>
<script src="/st.min.js"></script>
<script src="/app.js"></script>
</body>
</html>
HTML
} > "$dist/index.html"

# No inline JS may survive into the served HTML, or the CSP silently kills the page.
# Every <script> opening tag must carry a src=. (grep -E has no lookahead — list the
# tags, then assert none of them lacks src.)
if grep -oiE '<script[^>]*>' -- "$dist/index.html" | grep -qivE 'src='; then
  printf 'index.html contains an inline <script> — CSP script-src self would block it\n' >&2
  exit 1
fi

install -m 0644 -- gsap.min.js st.min.js "$dist/"

# --- scene assets ------------------------------------------------------------
if [[ -d assets/dist ]]; then
  mkdir -p -- "$dist/assets"
  find assets/dist -type f -print0 | while IFS= read -r -d '' f; do
    install -m 0644 -- "$f" "$dist/assets/$(basename -- "$f")"
  done
fi

printf 'built %s\n' "$dist"
find "$dist" -type f -printf '  %-22f %8s bytes\n' | sort
