#!/bin/sh
set -eu

BASE_URL="${1:-https://anime25d-rig.pages.dev}"
BASE_URL="${BASE_URL%/}"
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
STAGE=$(mktemp -d "${TMPDIR:-/tmp}/anime25d-web.XXXXXX")
trap 'rm -rf "$STAGE"' EXIT HUP INT TERM

FILES='
index.html
README.en.md
LICENSE
sample.psd
eye_close.psd
mouth_close.psd
lib/ag-psd.min.js
lib/rigger.js
lib/genericparts.js
lib/mediapipe/face_landmarker.task
lib/mediapipe/vision_bundle.mjs
lib/mediapipe/wasm/vision_wasm_internal.js
lib/mediapipe/wasm/vision_wasm_internal.wasm
lib/mediapipe/wasm/vision_wasm_module_internal.js
lib/mediapipe/wasm/vision_wasm_module_internal.wasm
lib/mediapipe/wasm/vision_wasm_nosimd_internal.js
lib/mediapipe/wasm/vision_wasm_nosimd_internal.wasm
'

for FILE in $FILES; do
    mkdir -p "$STAGE/Web/$(dirname "$FILE")"
    curl --fail --location --silent --show-error --retry 3 "$BASE_URL/$FILE" -o "$STAGE/Web/$FILE"
done

rm -rf "$SCRIPT_DIR/Web.previous"
if [ -d "$SCRIPT_DIR/Web" ]; then mv "$SCRIPT_DIR/Web" "$SCRIPT_DIR/Web.previous"; fi
mv "$STAGE/Web" "$SCRIPT_DIR/Web"
rm -rf "$SCRIPT_DIR/Web.previous"
echo "Bundled web runtime from $BASE_URL"
