#!/usr/bin/env bash
# NOTE: this script should be called from the parent directory to
# properly work

SCRIPT_DIR=$(dirname $0);
URL=${1:-http://localhost:9090}

echo "Preparing bundle for types from $URL"

set -ex

# Ensure clean working directory
rm -rf dist;
rm -rf node_modules;
rm -rf packages/server/dist;
rm -rf packages/server/node_modules;

pushd $SCRIPT_DIR;
set +e
./build-types $URL;
set -e
popd

pnpm -r --filter "!mcp-plugin" --filter "!mcp-browser-extension" install;
pnpm -r --filter "mcp-server" run build;

rsync -avr packages/server/dist/ ./dist/;

cp packages/server/package.json ./dist/;
cp pnpm-lock.yaml ./dist/;

# The standalone install needs the workspace policies (minimumReleaseAgeExclude,
# allowBuilds, overrides); storeDir and packages point to dev-only paths.
awk '/^storeDir:/ {next} /^packages:/ {skip=1; next} skip && /^[^[:space:]-]/ {skip=0} !skip' \
    pnpm-workspace.yaml > ./dist/pnpm-workspace.yaml;

cat <<EOF | tee ./dist/setup
#!/usr/bin/env bash
set -e;
command -v pnpm >/dev/null || { echo "error: pnpm not found in PATH" >&2; exit 1; };
pnpm install -P
EOF

chmod +x ./dist/setup;
