import { spawn } from "node:child_process";
import { withSiteBuildLock } from "./site-build.mjs";

const separator = process.argv.indexOf("--");
const command = separator >= 0 ? process.argv.slice(separator + 1) : [];
if (!command.length) {
  console.error("用法：node scripts/run-with-site-lock.mjs -- <部署命令> [参数]");
  process.exit(2);
}

await withSiteBuildLock(() => new Promise((resolve, reject) => {
  const child = spawn(command[0], command.slice(1), {
    stdio: "inherit",
    env: { ...process.env, YINZHUANG_SITE_LOCK_HELD: "1" },
  });
  child.on("error", reject);
  child.on("exit", (code, signal) => {
    if (code === 0) resolve();
    else reject(new Error(signal ? `部署命令被信号 ${signal} 终止` : `部署命令退出码：${code}`));
  });
})).catch((error) => {
  console.error(error instanceof Error ? error.message : error);
  process.exitCode = 1;
});
