#!/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}"
ARCHIVE="${REPO_ROOT}/dist/${NAME}.tar.zst"

if [[ ! -d "${DIST}" ]]; then
    echo "error: nothing built at ${DIST}; run 'just webbuild ${TARGET}' first" >&2
    exit 1
fi

# Archive the built web output (files at archive root). The host serves the
# unpacked files, so the archive only affects upload size -- use zstd at its
# max ratio (--ultra -22), which beats zip's DEFLATE substantially on the
# wasm-dominated payload while decompressing far faster than xz.
rm -f "${ARCHIVE}"
tar -C "${DIST}" -cf - . | zstd -q --ultra -22 -c > "${ARCHIVE}"

echo "wrote ${ARCHIVE}"
