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

rm -rf dist; mkdir dist

# Copy src to dist/src and build from dist/src into dist, so that
# the source map for index.js.map will refer to ./src/index.ts etc
cp -rp src README.md dist

for file in LICENSE; do
  if [ -e "../../${file}" ]; then cp "../../${file}" dist; fi
done

for file in CHANGELOG.md; do
  if [ -e "${file}" ]; then cp "${file}" dist; fi
done

# this converts the export map paths for the dist directory
# and does a few other minor things
PKG_JSON_PATH=../../packages/mcp-server/package.json node ../../scripts/utils/make-dist-package-json.cjs > dist/package.json

# updates the `cloudflare` dependency to point to NPM
node scripts/postprocess-dist-package-json.cjs

# build to .js/.mjs/.d.ts files
./node_modules/.bin/tsc-multi

cp tsconfig.dist-src.json dist/src/tsconfig.json

chmod +x dist/index.js

DIST_PATH=./dist PKG_IMPORT_PATH=cloudflare-mcp/ node ../../scripts/utils/postprocess-files.cjs

# mcp bundle
rm -rf dist-bundle cloudflare_api.mcpb; mkdir dist-bundle

# copy package.json
PKG_JSON_PATH=../../packages/mcp-server/package.json node ../../scripts/utils/make-dist-package-json.cjs > dist-bundle/package.json

# copy files
node scripts/copy-bundle-files.cjs

# install runtime deps
cd dist-bundle
npm install
cd ..

# pack bundle
cp manifest.json dist-bundle

npx mcpb pack dist-bundle cloudflare_api.mcpb

npx mcpb sign cloudflare_api.mcpb --self-signed

# clean up
rm -rf dist-bundle
