#!/bin/sh
set -ex

export PATH="$PWD/node_modules/.bin:$PATH"

for pkg in packages/core/* packages/react/*; do
    if [ -d "$pkg" ] && [ -f "$pkg/package.json" ]; then
        cd "$pkg"
        # Check if the package has a build script
        if node -e "const pkg = require('./package.json'); process.exit(pkg.scripts && pkg.scripts.build ? 0 : 1)"; then
            BUILD_CMD=$(node -e "const pkg = require('./package.json'); console.log(pkg.scripts.build)")
            if echo "$BUILD_CMD" | grep -q "radix-build"; then
                # Use the upstream builder to correctly compile all entry points including subpaths
                node ../../../internal/builder/radix-build.js .

                # Update package.json to point main, module, and promote/simplify publishConfig exports for Debian
                node -e '
                    const fs = require("fs");
                    const pkgPath = "package.json";
                    const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));

                    pkg.main = "./dist/index.js";
                    if (pkg.module) {
                        pkg.module = "./dist/index.mjs";
                    }

                    // Promote publishConfig exports to top-level and simplify subpath exports for Debian extlinks
                    if (pkg.publishConfig && pkg.publishConfig.exports) {
                        pkg.exports = pkg.publishConfig.exports;
                        if (pkg.exports["./is-development"]) {
                            pkg.exports["./is-development"] = {
                                "types": "./dist/internal/is-development.false.d.ts",
                                "require": "./dist/internal/is-development.false.js",
                                "import": "./dist/internal/is-development.false.mjs"
                            };
                        }
                    } else if (pkg.exports) {
                        delete pkg.exports;
                    }

                    fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
                '
            else
                sh -c "$BUILD_CMD"
            fi
        fi
        cd - > /dev/null
    fi
done
